Monday, December 8th, 2008
Do you ever get frustrated with creating columns of equal size using CSS? If you are, you have the same feeling as many of us developers. Creating faux columns is one option, but may I suggest using JQuery to make this process a synch. In the following tutorial we will be creating a JQuery Plug-in that will allow us to use a single line to make our divs equal heights.
Note: Please visit, CSSNewbie to get another similar approach. I have taken some ideas from this post, but have implemented it as a plug-in unlike his example.
Below shows the problem:

First of all, shuffle over to JQuery.com like always and download the latest JQuery version. Place this file in a folder called “js”. Now let’s build our structure and presentation:
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Equal Heights using JQuery:: Brenelz.com</title>
<style style="text/css">
body { font: 0.75em Arial, Helvetica, sans-serif; background-color: white; }
#wrapper { width: 760px;margin: 0 auto; }
.column {float: left; padding: 10px; }
#col1 { width: 110px;margin-right: 10px;background-color: #E2DDC4; }
#col2 {width: 200px;margin-right: 10px;background-color: #B5C9DA; }
#col3 {width: 210px;background-color: #E87C5E; }
</style>
<script type="text/javascript" src="js/jquery-1.2.6.pack.js"></script>
</head>
<body>
<div id="wrapper">
<h1>Equal Heights Using JQuery</h1>
<div class="column" id="col1">
<p>This three-column design features three columns with significantly varying quantities of content.</p>
</div>
<div class="column" id="col2">
<p>Normally these divs would all be different heights but using JQuery we can make them all the same heights. No faux columns, or other repeating background tricks are needed!</p>
<p>They're simply individual divs sharing the same class name, which we can use in our JQuery.</p>
</div>
<div class="column" id="col3">
<p>And this can be done using a custom plug-in and 1 line of JavaScript!</p>
</div>
</div>
</body>
</html>
Nothing too complicated here. I am going to assume you have basic knowledge of HTML and CSS, so we can focus on the JQuery. Let’s add a touch more JavaScript to our head that will represent what we want to do.
<script type="text/javascript">
$(function(){
$('.column').equalHeight();
});
</script>
This won’t work yet obviously because equalHeight() is not a function that JQuery comes with by default. I will now show you how to make a custom plug-in.
<script type="text/javascript" src="js/jquery.equalHeight.js"></script>
Now that the files are all linked up lets edit our jquery.equalHeight.js:
// make sure the $ is pointing to JQuery and not some other library
(function($){
// add a new method to JQuery
$.fn.equalHeight = function() {
// find the tallest height in the collection
// that was passed in (.column)
tallest = 0;
this.each(function(){
thisHeight = $(this).height();
if( thisHeight > tallest)
tallest = thisHeight;
});
// set each items height to use the tallest value found
this.each(function(){
$(this).height(tallest);
});
}
})(jQuery);
Save this file and open it up. You should now see that each DIV has the same height.

I hope you have learnt the basics of JQuery, along with learning how to extend JQuery for your future projects. Â Please download the JQuery Equal Height Tutorial Files, and feel free to fiddle around with the code.
Tags: JavaScript, jquery
Posted in Web Programming | 11 Comments »
Tuesday, December 2nd, 2008
JQuery has quickly become my preferred framework. It has a relatively small footprint and offers a lot of functionality with little code. Today we will be using this library to create a simple accordion which you can use on your website, or blog.
Download my JQuery Accordion example here or View the JQuery Accordion Screencast
First of all, please visit JQuery’s site and download the production code. Then proceed to include this into your HTML file, using something similar to the below in the <head> section:
<script type="text/javascript" src="js/jquery-1.2.6.pack.js"></script>
Now let’s begin to create our simple mark-up for our accordion.
<div class="accordion">
<h3>Heading One</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi malesuada, ante at feugiat tincidunt, enim massa gravida metus, commodo lacinia massa diam vel eros. Proin eget urna. Nunc fringilla neque vitae odio. Vivamus vitae ligula.</p>
<h3>Heading Two</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi malesuada, ante at feugiat tincidunt, enim massa gravida metus, commodo lacinia massa diam vel eros. Proin eget urna. Nunc fringilla neque vitae odio. Vivamus vitae ligula.</p>
<h3>Heading Three</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi malesuada, ante at feugiat tincidunt, enim massa gravida metus, commodo lacinia massa diam vel eros. Proin eget urna. Nunc fringilla neque vitae odio. Vivamus vitae ligula.</p>
</div>
We are just using H3 tags for our headings and a paragraph tag which would contain your actual content. This is not looking too pleasing yet. Add the below CSS and then view the HTML file once again.
<style type="text/css">
body {
margin: 10px auto;
width: 570px;
font-size: 0.75em;
font-family: Arial, Helvetica, sans-serif;
}
.accordion {
width: 480px;
border-bottom: solid 1px #c4c4c4;
}
.accordion h3 {
background-color: #e9e7e7;
padding: 7px 15px;
margin: 0;
font-size: 1.2em;
border: solid 1px #c4c4c4;
border-bottom: none;
cursor: pointer;
}
.accordion h3:hover {
background-color: #DFD1D1;
}
.accordion h3.active {
background-color: #D1D1DF;
}
.accordion p {
background: #f7f7f7;
margin: 0;
padding: 10px 15px 20px;
border-left: solid 1px #c4c4c4;
border-right: solid 1px #c4c4c4;
display: none;
}
</style>
Most of the above is pretty self explanatory and mostly has visual meaning. The most important aspect to see is that we have set “display:none” to each accordion paragraph. If you have seen an accordion you know that the content is not shown until a heading is clicked.
Another selector that you might not see point in at the current moment is the class “active”. This will be assigned to whichever heading has been clicked, as to provide the user with a visible clue as to which content they are seeing.
Enough of the XHTML / CSS work…. you came here for the JQuery right? Let’s pseudo code out what we want our JavaScript to do. The following corresponds to the line numbers in the below code.
Now let’s write out the JQuery to accomplish each of these tasks:
$(function(){
$(".accordion h3").eq(2).addClass("active");
$(".accordion p").eq(2).show();
$(".accordion h3").click(function(){
$(this).next("p").slideToggle("slow")
.siblings("p:visible").slideUp("slow");
$(this).toggleClass("active");
$(this).siblings("h3").removeClass("active");
});
});
Now test this out in a browser and be wowed as how simple it was to create a neat accordion with 10 lines of code!
If you enjoyed this JQuery tutorial, make sure to comment and let me know what other JQuery tutorials you are looking for.
Tags: JavaScript, jquery
Posted in Web Programming | 5 Comments »
Tuesday, November 25th, 2008
I have attempted something new, as this is my first screencast ever! As expected you may have to bear with me for a bit while I get used to it. Please feel free to comment on suggestions I can make. Below you can find links to the starting files, as well as the complete end product.
Starting Files
Complete Files
Below is a text version:
Today we will be coding a fully-functional, cross-browser hover menu using CSS and Javascript.
Let’s go to our index.html file and create some mark-up which we can use for our menu.
<div id="globalNavDiv">
<ul>
<li><a href="#">Menu 1</a></li>
<li><a href="#">Menu 2</a></li>
</ul>
</div>
These are the links that we will mouse over and thus causing the submenu of that particular link to show up. Let’s create the mark-up for those submenus right under our globalNavDiv.
<div id="submenu1">
<a href="#">Menu Item 1</a>
<a href="#">Menu Item 2</a>
<a href="#">Menu Item 3</a>
</div>
<div id="submenu2">
<a href="#">Menu Item 1</a>
</div>
Now take a look at it in the browser. As you can see it isn’t looking too pretty yet, but it’s a start. We now need to style our elements in our external css file. Open up our styles file and begin entering the following.
#globalNavDiv ul
{
border: 1px solid #a3a3a3;
}
#globalNavDiv li
{
display: inline;
padding: 0px 10px;
}
#globalNavDiv li a
{
color: #575757;
font-size: 1.2em;
font-weight: bold;
text-transform: uppercase;
text-decoration: none;
}
#globalNavDiv li a:hover
{
color: #353535;
}
#submenu1, #submenu2
{
background-color: #820024;
border: 1px solid #a3a3a3;
z-index: 1000;
}
#submenu1 a, #submenu2 a
{
border-top: 1px solid #fdd3df;
display: block;
color: #fdd3df;
text-decoration: none;
padding: 5px 15px 5px 5px;
}
#submenu1 a:hover, #submenu2 a:hover
{
color: #ffffff;
}
Now take a look in the browser once more. As you can see we have now styled our main and sub menus. The problem is that our submenus are not in the right position. Let’s change that now:
#wrapperDiv
{
position: relative;
}
#submenu1, #submenu2
{
position: absolute;
top: 0px;
}
#submenu1
{
left: 0px;
}
#submenu2
{
left: 0px;
}
Now we have absolutely positioned each of our submenus to the top left corner of our wrapperDiv. Let’s use firebug to align our submenus to the bottom of our main menu links. This ends up being 20px. Let’s change this permanently in our styles file.
#submenu1, #submenu2
{
top: 20px;
}
Continue using firebug to specify a left value to each.
#submenu1
{
left: 50px;
}
#submenu2
{
left: 120px;
}
Perfect! Now the one problem we still have is that the divs are shown by default. Lets hide these divs now:
#submenu1, #submenu2
{
visibility: hidden;
}
The only thing left to do now is create the JavaScript code and attach it to the HTML. First lets create an array with all the ids of the submenus
var menuArray = new Array(); menuArray[0] = 'submenu1'; menuArray[1] = 'submenu2';
Then initialize some variables we will use in our functions.
var globalObject = ''; var isActive = false; var ourTimer;
Now we will need to create 4 functions; one to show and hide the correct div, another to start our timer and hide the menu when it ends, another that physically hides the menu if it’s not active, and lastly one that checks if the mouse is still over the div.
function showhide(obj, onlink)
{
targetObject = document.getElementById(obj).style;
globalObject = targetObject;
if(onlink)
{
clearTimeout(ourTimer);
for (i=0; i < menuArray.length; i++)
{
var tempObject = document.getElementById(menuArray[i]).style;
tempObject.visibility = "hidden";
}
targetObject.visibility = 'visible';
isActive = true;
}
else
{
isActive = false;
layerTimer();
}
}
function layerTimer()
{
ourTimer = setTimeout("hideMenu()",0750);
}
function hideMenu()
{
if( !isActive )
{
globalObject.visibility = 'hidden';
}
}
function layerCheck(flag)
{
if(flag)
{
isActive = true;
clearTimeout(ourTimer);
}
else
{
isActive = false;
layerTimer();
}
}
Now let’s attach the above functions to our HTML file. Create a function that triggers when the page loads and assigns each submenu div to fire the layerCheck when moused over or moused out.
window.onload = function()
{
for(var i=0;i<menuArray.length;i++)
{
var id = menuArray[i];
var e = document.getElementById(id);
e.onmouseover = function(e)
{
layerCheck(true);
}
e.onmouseout = function(e)
{
layerCheck(false);
}
}
}
Now lastly we need to trigger our showhide function when each of our main links is moused over or moused out.
<li><a href="#"
onmouseover="showhide('submenu1', true); return false;"
onmouseout="showhide('submenu1', false);">Menu 1</a>
<li><a href="#"
onmouseover="showhide('submenu2', true); return false;"
onmouseout="showhide('submenu2', false);">Menu 2</a></li>
Now peak over to both Firefox and Internet Explorer 7 and see that we now have a fully functional Hover Menu.
Tags: css, html, JavaScript, screencast
Posted in Web Programming | 3 Comments »
Monday, November 17th, 2008
Unobtrusive JavaScriping is a very crucial part of designing a website. As you should know there are 3 major layers of the web, and they should all be separated into external files. You have XHTML (structure), CSS (presentation), and JavaScript (behavior).
Separating these three pillars of the web will go a long way towards maintainability of the code you produce. The reason I am focusing on the external JavaScript portion is because I find it one of the more difficult. It takes a lot of discipline to stay away from putting even handlers into the code. Today I will be talking about the concept of unobtrusive JavaScript, as well as provide you with a tool that will make your life easier.
Unobtrusive JavaScript is a process by which you make your JavaScript as user-friendly, accessible, and maintainable as possible. It supports graceful degradation in older browsers, and provides separation of behavior from structure. The following are some simple rules I have come up with:
Using those inline event handlers are so handy, but really it is just as bad as using the dreaded style tags within your code. Remember that we want to keep things separated as best we can. The following is how you can add a simple event handler to a link in an accessible way:
<a href=”login.php” id=”login” title=”Login to Admin”>Login</a>
// when our document is loaded
window.onload = function()
{
// check browser support
if(!document.getElementById){ return; }
// get element
var e = document.getElementById('login');
// when our element is clicked call a function
e.onclick = clickHandler;
}
function clickHandler(e)
{
// fancy ajax code entered here
alert('JavaScript took over the link');
// cancel the default browser action
// This works in Firefox - keeping this example simple
e.preventDefault();
}
Now the JavaScript portion can be put in an external JavaScript file and we can keep our HTML nice and clean.
Beginners to web design often like the power of JavaScript and they develop using it for everything. As with any programming language you need to use the proper tool for the job, and whether or not you are using it for the “cool” factor or if it will actually help the user. Links such as the following are big no-no’s and show that the user is assuming JavaScript is enabled:
<a href="#" onclick="popup('web-development.html');return false;">Web Development</a>
<a href="javascript:popup('web-development.html')">Web Development</a>
Do you know what happens when JavaScript is disabled? You guessed it nothing. The visitor is left thinking, “Why does this link do nothing?” The following is a better way of handling the above:
<a href="web-development.html" onclick="popup(this.href);return false;">Web Development</a>
Now if JavaScript is disabled, at least the user will be redirected to the appropriate page even though it might not be in a pop up. You may be wondering why I used the onclick attribute… It is solely to cut down code in this example. You know that this should be put in an external JavaScript file.
The other day I found this nifty Firefox tool that allows you to check if there are any problems with obtrusive JavaScript within a page. It shows the number of inline events, “javascript: links”, as well as many other useful features to keep you disciplined. Please visit the Obtrusive JavaScript Checker plug-in page.
Tags: JavaScript, unobtrusive
Posted in Uncategorized | 3 Comments »
Thursday, November 13th, 2008
Creating a Google map is almost a requirement in every website I design these days. Google maps have been the showcase for AJAX ever since it was coined. Google Maps are interactive maps that you can embed within your web page using Google’s already built API.
When I began embedding Google Maps in my web pages, one of the clear limitation I found was needing to specify a latitude and longitude. This was the only way I knew how to use the maps. This worked fine for a little while as I mainly used them on contact forms with fixed places. I found sites that helped me identify a latitude / longitude and then I plunked it in the code.
Eventually this theory didn’t work as now I needed to implement this Google map to use dynamic addresses to find the right location. Remember, all I knew was to implement it using lat / long coordinates. This would force me to store these two values in a database. This of course isn’t very user friendly for the client I am setting up the administration for. They have no clue what these values are, and why should they? They want to just enter the address.
This is when I found out that Google Maps offers a simple way for which to translate an address into its corresponding lat / long coordinates. The theory is called Geo Coding. Here you can view Google’s Geo Coding Documentation. This in the end is a much more practical way of dynamically creating a Google Map. You can now pull the address from the database and insert it into the JavaScript code. Below is an example (I have assumed you have a Google map API key, as well as included the appropriate base script)
var map = null;
var geocoder = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(49.843774, -99.961166), 13);
geocoder = new GClientGeocoder();
address = '< ?php echo $address ?>';
if (geocoder) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert("Google map for "+address + " could not found");
} else {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml(address);
}
}
);
}
}
}
Now all that is needed is for you to place the container somewhere in the body of your HTML:
<div id="map_canvas" style="width: 300px; height: 300px"></div>
Now the other benefit you see is that you can reuse this Google Map code whenever you need to, and you don’t need to find out those blasted lat / long coordinates!
Tags: google maps, JavaScript
Posted in Web Programming | No Comments »
Twitter
Follow me on Twitter to keep up to date!
RSS Feed
Keep up with all of our updates by subscribing to our RSS feed!
FaceBook
Join our group on Facebook and become a fan of us!