jQuery Fundamentals–Part 1–Hello jQuery!

Down Arrow

As part of this blog I plan to write several long running series of shorts. Today I want to open up a new series on the fantastic Cross-Browser JavaScript Library jQuery. jQuery makes easy work of many of those common tasks that in years gone by we’d write and re-write again and again to achieve simple goals such as DOM traversing and Event Handling.

jQuery Training

 

 

I will start this series with the timeless ‘Hello World!’ example in which we will use jQuery to attach a click event to a button, that upon clicking will display an alert. First we need to create our HTML document which should look something like this:

<html> <head> <title>Hello jQuery</title> </head> <body> </body> </html> 


We must start by referencing the jQuery library in the head of our page:

    <script type="text/javascript" src="Scripts/jquery.js"></script> 


Secondly, we need to insert our button in to the body of our page so that our page now looks like this:

<html> <head> <title>Hello jQuery</title> <script type="text/javascript" src="Scripts/jquery.js"></script> <script type="text/javascript"> $(document).ready(function () {
$("input").click(function () {
alert("Hello jQuery!");
});
});
</script> </head> <body> <input id="HelloButton" type="button" value="Say Hello" /> </body> </html>

The first thing to learn about jQuery is the ‘ready’ event. The ready event fires as soon as the Document Object Model (DOM) has finished loading. This signifies the time when we can be sure that the button exists and therefore we can go ahead and add the click event to it. To register a ‘ready’ event for the document we use the following syntax.

$(document).ready(function () {
//The DOM is ready. Go Wild!
});


The $() syntax signifies jQuery and you can replace this with jQuery() if you would prefer, but the recognised convention is to use the former syntax for simplicity. Finally, we need to hook up our event as shown below:

The above code will traverse the entire DOM and attached our click event to all the input tags that it comes across. The benefits of this are obvious as we no longer need to go and add a click event to every button manually and if we decide that we want to change the functionality at a later date then we only need to make the change in one place so we can be sure that we don’t miss one of our buttons. However, if we want to attach our event only to our button named HelloButton the we can use the following syntax instead.

$(document).ready(function () {
$("#HelloButton").click(function () {
alert("Hello jQuery!");
});
});


image
That’s enough of an introduction for now. In future posts we’ll delve deeper in to how jQuery can make our lives providing interactivity to websites easier.

Mark

SHARE
comments powered by Disqus

Get in touch today!

Start your project