Briefly, jQuery is a free and open-source JavaScript library designed to make life easier when implementing client-side controls using JavaScript. However, this simple explanation belies a subtle but immensely important principle - separation of concerns.
Just as HTML and CSS each have separate responsibilities when rendering a web-page (HTML dictates the structure of the page, while CSS controls its presentation), so too is the case with jQuery - its responsibility is to control the behaviour of the page, removing the need to embed JavaScript events within HTML markup.
For example, consider the following traditional HTML snippet:
<a href="" onmouseover="alert('Pop!');">Surprise</a>
This is rather spurious, but you get the idea - we have a link which pops up a message box when the mouse goes over it.
The problem is that we have JavaScript embedded in our HTML markup - a bad idea.
Sure, we could move alert('Pop!'); to an external JavaScript file and reference it via a <script> tag in the header - this is an improvement, but we still need the onmouseover attribute to exist as part of our HTML in order to link the JavaScript to our field.
jQuery provides a way of avoiding this - our HTML no longer requires events to be associated with specific elements:
<a id="surprise" href="">Surprise</a>
Note that we have added an id attribute which can be referenced both from CSS and jQuery - we now need to add our JavaScript to the <head> of the page as follows:
<script type="text/javascript" src="scripts/jquery-1.3.2.min.js"/>
<script type="text/javascript">
jQuery(function() {
$("#surprise").mouseover(function() {
alert('Pop!');
});
});
</script>
The first line includes the jQuery library, while the rest implements our event.
Don't worry about the syntax for now - what we're doing here is attaching a function to the mouseover event on any DOM object that has id of 'surprise' (since it's an id reference, there can only be one).
As expected, our function once again displays our popup alert, but without any dependency on the HTML markup - good separation of concerns!

0 comments:
Post a Comment