Unobtrusive JavaScript and events
Where are we at?

In the first part of this tutorial, we downloaded the jQuery libraries, configured our web server (hopefully that went well, as I didn’t tell you how to do it) and wrote an incredibly trivial little sample page to get us started. With that basic ”Hello World” type activity out of the way, we can move on to more powerful jQuery.
Let’s face it. Coding in JavaScript is a colossal pain in the rear, especially when you start embedding it into your html, i.e.:
<html>
<body>
<input type=”button”id=”TestButton” value=”Test Button”
onclick=”alert(‘click’)”/></body>
</html>
Your html becomes littered with stuff like this, and the markup gets mixed up and next thing you know, anarchy reigns. Basically, you’ve got a cat living in your doghouse. It just doesn’t belong there.
Fortunately, JavaScript doesn’t require it there, but that means you’ll need to look up your html element and then add the click event to it. Again, this is probably not the best use of your time. As you might surmise, jQuery has a very clean solution to this in the form of the jQuery selector which allows you to select the elements you need from a page and do whatever you want to them.
So, in JavaScript, to find an element, and add a click event, you either need to use the code/html integrated slop, or you need something like:
<html>
<head>
<script type=”text/javascript” language=”JavaScript”>
function setClick(elementId)
{
var element = document.getElementById(elementId);
if (element!=null)
{
if (element.attachEvent)
element.attachEvent(“onclick”, function() { alert(‘clicked’) } );
}
}
</script>
<body onload = “setClick(‘button1′)” >
<form id=”myForm” >
<input type=”button” value=”myText” id=”button1″ >
<input type=”button” value=”myText2″ id=”button2″>
</form>
</body>
</html>
Now, technically, this is unobtrusive JavaScript. There is no markup in the actual code, so we are all happy right? Wrong. Look at that code!! There is a ton of it, and as I indicated earlier, writing JavaScript code sucks and debugging it is about as fun as a root canal.
Let’s look at the same thing but this time, we will use the miraculous and all-encompassing silver bullet that is jQuery (if you think that last sentence is serious, I would advise you to pick a different vocation). Anyway, in jQuery it will look like:
<html>
<head>
<script src=”jquery-1.4.2.min.js” type=”text/javascript”>
</script>
<script type=”text/javascript”>
$(document).ready(function()
{
$(“#button1″).click(function() { alert(‘button1′); } );
}
);
</script>
<body>
<form id=”myForm” >
<input type=”button” value=”myText” id=”button1″ >
<input type=”button” value=”myText2″ id=”button2″>
</form>
</body>
</html>
Admittedly, the plain old vanilla javascript version is only 2 lines longer than the jQuery version, but the jQuery version is simpler by far. Plus, to add a click event for the second button, all you would need to do is:
$(“#button2”).click(function() { alert(“button2”); });
In Javascript, you would need to create a function to allow you to do multiple setClicks in one onload (or even worse, just string them together) and once again, we start getting really ugly code. As the complexity of your code increases, this is going to turn into some really nasty looking stuff.
Our jQuery solution is much more elegant. This elegance is delivered to us by the power of the jQuery selector. In the above code, where we write:
$(“#button2”)… We are telling jQuery “get me the element (or elements) matching the expression #button2.” Now, we know what “button2”is, but the # in front of it is a little mysterious, at least in javascript.
If you are familiar with cascading style sheets (CSS) it’s not so mysterious. “#” indicates an element id. So “#button1” is any button with an id field equal to “button1.” But that’s just the start! The javascript selector can use pretty much ALL of the CSS selectors to find elements, and this is where it really blows the doors off of plain old javascript.
For example, in the above code, if we had 20 buttons and we wanted to set their click events to all point to the same method, we’d need to jump through various hoops to do it, with either an array of button names, or some string manipulation or something to help us get through our list of buttons. In jQuery, we can just do this:
$(document).ready(function()
{
$(“input[type='button']“).click(function() { alert(this.id); } );
}
);
This says that for each and every input of type button, set its click button the provided function (you can specify any function, either inline or external, as long as it matches the event’s signature).
But now, you will likely be concerned that this will match it for EVERY button on the entire page, and you only really want it to happen for ids starting with ‘buttonup’. Then, you can simply do this:
$(“input[id^='buttonup']“).click(function() { alert(this.id); } );
But now, you are going to complain that “I only want BUTTONS beginning with buttonup. I have some checkboxes named that too, and I only want buttons…” Well, work on your naming conventions, but in the meantime, just like with CSS you can chain multiple selectors. The code below will accomplish this quite nicely:
$(“input[id^='buttonup'][type='button']“).click(function()
{
alert(this.id); } );
}
Of course, if you are a real CSS fan, you aren’t going to do that. You are simply going to create a class such as:
.buttonUp
{
….
}
And set your button’s class attribute to this. You are using CSS right? Not formatting with tables right? Good! So now, you can just use your nice CSS class:
$(“.buttonUp”).click(function(){alert(this.id); });
Pretty slick huh? The selectors are incredibly powerful. Without them, I honestly don’t think jQuery is anything too amazing. But with them, it helps change javascript from a hated enemy to a friend, or at very least a tolerable acquaintance.
Summary
We covered two very important concepts in this part of the tutorial. First, we took a look at unobtrusive javascript and what it buys us. Then we took a peek at the jQuery selector. The jQuery selector is an incredibly powerful concept and will require some more examination. In the next section, we’ll do just that, digging into more of the fun stuff we can do with jQuery.





No Responses to “Get Rolling With jQuery – Part 2”