Tuesday, June 22, 2010

jQuery is what JavaScript should have been - introduction and examples

jQuery is what Javascript should have been - introduction and examples
Please note this is not an extensive jQuery tutorial, it is more about how jQuery is the better option for client side browser scripting compared to javaScript and is aimed at people looking to change over from one to the other. jQuery is a framework that uses javascript to 'write less and do more'.

jQuery is what Javascript should have been. This is most definitely true, but is somewhat harsh I think. Javascript was created by Netscape as a language that allowed the programmer/developer of the website to manipulate the various elements of a web page. It was called JavaScript after Sun licenced their Java brand name to give the language a little more credibility. JavaScript allowed the creators of the website to display and showcase the content with a little more flair.

Like a lot of things on the Internet, the use of JavaScript was exploited and made web surfing painful at times. JavaScript can be used to open multiple windows at once and these 'popups', especially when a user was connected to the 'net using a dial up connection and tens of windows would open up simultaneously offering you products ranging from hair extensions to god knows what. Popups thankfully became less of a problem as browsers and firewall software improved including pop up blockers.

Another problem and some may argue a bigger problem was the way the software ran in browsers. Javascript was created by Netscape and was thus adopted by other browsers, unfortunately the language was not adopted as a standard and the browsers (namely Internet Explorer) did not all act the same when they came across JavaScript - this gave developers a huge problem. Scripts had to be tested in mutliple browsers and debugging time obviously shot through the roof.

This is where the wonder of jQuery comes rushing through. JavaScript had started to be used more and more as many online applications needed the little bit of extra functionality to deliver. jQuery took away the need for writing scripts for multiple browsers. You could in a reduced manner add in code in one line that would without jQuery library taken 10 or so line of code. It really did make it that easy.

Below are a number of examples of some of the more common tasks that you can use JavaScript for. Starting with the basic task of obtaining an element's value right through to the more advanced method of making an AJAX call. Each example will have the jQuery code followed by the JavaScript that would have been necessary without the jQuery library. jQuery also allows for developers to easily add events to elements, i.e. a mouse click. This is where we will begin as it one of the cornerstones of using jQuery and using for the coding on the web.

For the sake of this tutorial, I will be an using an element named 'myElement' - which could be anything like a paragraph, div, input. If any other elements are used or are a special, I will explain further where necessary.

You will see the $ sign a lot throughout this exercise, it basically means let jQuery handle the code.

Adding an event in jQuery:

This is how you add an event in jQuery:
$('#myElement').click(function(){
alert('Hello World');
});


Like with all jquery it works in all browsers, now lets take a look at the above in plain JavaScript, unfortunately there are a number of issues when it comes to adding event handlers - Internet Explorer. Microsoft, in their infinite wisdom decided to add their own event handling system.

Here is the the code according to w3c specification - i.e. for Firefox, Opera, Chrome using an anonymous function as the second parameter - you could as easily add a reference to another function, i.e. myFunction() instead like I have shown on the Internet Explorer example below

myElement.addEventListener('click',function(){
alert('Hello World')
},false);


The 3rd parameter given here as boolean = false refers to refers to event bubbling and that goes beyond the scope of this introduction, rest assured though, jQuery makes that easier too!

Here is the code for Internet Explorer

myElement = document.getElementById('myElement');
myElement.attachEvent('onclick',myFunction);


The problems here not only lead to writing more code to get the reference for the variable, address both w3c spec and non w3c spec browsers but you may also have to write code that detects the browser type so that your script doesn't cause errors.

Getting the value of a input form field

This includes select inputs and and select, most form values- I know, how easy...

var myVar = $('#myElement').val();

Now let's look at this in plain JavaScript to obtain a text input value:

var myVar = document.getElementById('myElement').value;

For a select dropdown menu it's even more cumbersome, not only do you have to select the element from a form, but you have to go through the array of options to find the value:

var mySelectDropDown = document.forms['myForm'].mySelect;
var selectChoice = mySelectDropDown[mySelectDropDown.selectedIndex].value;


Modifying an Element's CSS property

Let us look at this in jQuery:

$('#myElement').css('background-color','#000000');

Now let us look at this in JavaScript:

In this case we are going to change the background color of an element and set it to black(#000000). First we have to find the element using the document.getElementById() function. We then have to name the CSS property

myElement = document.getElementById(myElement')
myElement.style.backgroundColor = "#000000";


Again, how much easier is this? The added bonus is that it uses the same referencing system that you may be used to using in CSS, rather than a different reference, again saving you time and effort.
On to Ajax...

Performing jQuery Ajax calls couldn't be easier. This example uses a the .open() method, but there are a number others you may be interested in, namely $.get() and $.post(), so you may want to read up on them later. The following example takes the contents of another page and then adds the content to the element:

$('#myElement).open('myOtherPage.html);

Now let's look at that in plain JavaScript:

//first we have to create the XmlHttpRequestObject
var myAjaxObject = createXmlHttpRequestObject();
//then we create the function that triggers the event
function getContents() {
//reference the source to open
myAjaxObject.open('get', 'myOtherPage.html);
//assign the function that will handle the response
myAjaxObject.onreadystatechange = handleInformation;
//declare extra parameters, not needed when using the get method
myAjaxObject.send(null);
}
//now we have to create the function to handle the above:
function handleInformation() { //check the state of the request
if(myAjaxObject.readyState == 4 && myAjaxObject.status == 200) {
//Add the information to the myElement ID
myElement = document.getElementById('myElement');
myElement.innerHTML = myAjaxObject.responseText;
}
}

Hope this helps.

Labels: , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home