• Home

Logo

Navigation
  • Home
  • Articles
    • Content Writing
    • Design
    • General
    • Internet Marketing
    • Social Media
    • Tools and Tips
    • Usability
    • Web Hosting Articles
  • Tutorials
    • AJAX Tutorials
    • ASP Tutorials
    • C# Tutorials
    • CGI and Perl Tutorials
    • CSS Tutorials
    • Flash Tutorials
    • HTML Tutorials
    • Illustrator Tutorials
    • Java Tutorials
    • JavaScript Tutorials
    • Linux Tutorials
    • Miscellaneous Tutorials
    • MySQL Tutorials
    • Photoshop Tutorials
    • PHP Tutorials
    • Python Tutorials
    • Wireless Tutorials
    • WordPress Tutorials
    • XML Tutorials
  • Scripts
    • AJAX Scripts
    • ASP Scripts
    • ASP.NET Scripts
    • CGI & Perl Scripts
    • Flash Scripts
    • Java Scripts
    • JavaScript Scripts
    • PHP Scripts
    • Python Scripts
    • Remotely Hosted
    • Tools and Utilities
    • XML Scripts
  • Answers
  • Online Services
  • Tools

Get Rolling With jQuery – Part 2

By Larry Schoeneman | on Aug 3, 2010 | 0 Comment
AJAX Tutorials JavaScript Tutorials
  • Tweet
  • Share
  • Tweet
  • Share

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.

Share this story:
  • tweet

Author Description

Larry Schoeneman is a software developer with over 20 years of experience, focused on Microsoft products and technologies as well as utilizing agile methodologies to build better software.

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

You must be logged in to post a comment.

Connect With Us

RSSSubscribe 1,242Followers 492Likes
  • Popular
  • Recent
  • Comments
  • Creating Energy Spheres in Photoshop

    Apr 15, 2008 - 96 Comments
  • Easy Screen Scraping in PHP with the Simple HTML DOM Library

    Aug 6, 2008 - 20 Comments
  • Calculating date difference more precisely in PHP

    Mar 7, 2008 - 13 Comments
  • When Does Hosting Your Website in the Cloud Make Sense?

    Oct 8, 2010 - 2 Comments
  • Fun with the Microsoft Managed Extensibility Framework Part 2

    Oct 6, 2010 - 0 Comment
  • Fun with the Microsoft Managed Extensibility Framework Part 1

    Sep 22, 2010 - 0 Comment
  • Website Management on the go with the iPad

    I appreciated your post, but I was looking for something I didn't...
    November 24, 2012 - drmoderator
  • Creating Energy Spheres in Photoshop

    I'm a little stuck down here especially at the step of creating the...
    November 23, 2012 - sarah
  • Running background processes in PHP

    Can you give an example? As see it, you can use this only when you...
    November 16, 2012 - Shaked Klein Orbach
Developer Resources
  • Tutorial Directory
  • Learn HTML
  • Learn PHP
  • Learn CSS
  • Learn AJAX
  • Learn JavaScript
  • Learn Pear
  • White Papers
  • Resources
    • NetVisits Web Directory
    • Realtor Pixels
    • Answers On The Run
    • Ask A Geek
  • Recent Posts

    • When Does Hosting Your Website in the Cloud Make Sense?
    • Fun with the Microsoft Managed Extensibility Framework Part 2
    • Fun with the Microsoft Managed Extensibility Framework Part 1
    • Website Management on the go with the iPad
    • Code Contracts in C# 4.0 – Part 1

    Calendar

    May 2013
    M T W T F S S
    « Oct    
     12345
    6789101112
    13141516171819
    20212223242526
    2728293031  

    Recent Comments

    • drmoderator on Website Management on the go with the iPad
    • sarah on Creating Energy Spheres in Photoshop
    • Shaked Klein Orbach on Running background processes in PHP
    • Thomas Cuvillier on How To Upload Files Using PHP
    • rizal aditya on Extracting text from Word Documents via PHP and COM
    • Home
    © 2003 - 2013 DeveloperTutorials.com. All Rights Reserved. Privacy Policy.