jQuery Primer in Html5

jQuery Primer in Html5

Writing JavaScript that works well across all major web browsers in a clean and concise way is a difficult chore. There are many libraries that make this process less painful, and jQuery is one of the most popular. It’s easy to use, has a wide array of existing libraries, and is a good fit for easily creating fallback solutions. This appendix introduces you to the parts of the jQuery library that we use elsewhere in the book. It’s not meant to be a replacement for jQuery’s excellent documentation, 1 nor is it going to be an exhaustive list of the features and methods available. It will, however, give you a good place to start jQuery Primer in Html5.

Loading  jQuery Primer in Html5

You can grab the jQuery library from the jQuery website 2 and link to the jQuery script directly, but we’ll load jQuery from Google’s servers, like this jQuery Primer in Html5:

<script type= "text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" >

Browsers can make only a few connections to a server at a time. If we distribute our images and scripts to multiple servers, our users can download our pages faster. Using Google’s content delivery network has an additional benefit as well—since other sites link to the jQuery library at Google, our visitors may already have the library cached by their browser. As you probably already know, browsers use the full URL to a file to decide whether it has a cached copy. If you plan to work with jQuery on a laptop or on a computer without constant Internet access, you will want to link to a local copy instead jQuery Primer in Html5.
jQuery Basics jQuery Primer in Html5
Once you have loaded the jQuery library on your page, you can start working with elements. jQuery has a function called the jQuery( ) function. This one function is the heart of the jQuery library. We use this function to fetch elements using CSS selectors and wrap them in jQuery objects so we can manipulate them. There’s a shorter version of the jQuery( ) function, $();, and that’s what we use in this book. Throughout the rest of this appendix, I’ll refer to this function as “the jQuery function.” Here’s how it works: If you wanted to find the h1 tag on a page, you’d use the following jQuery Primer in Html5:

$("h1" );
$(".important" );

Take a look at that again. The only difference between those two examples is the CSS selector we used. The jQuery function returns a jQuery object, which is a special JavaScript object containing an array of the DOM elements that match the selector. This object has many useful predefined methods we can use to manipulate the elements we selected. Let’s take a look at a few of those in detail. Methods to Modify Content We use several jQuery methods to modify our HTML content as we work through this book.
Hide and Show to jQuery Primer in Html5
The hide( ) and show( ) methods make it easy to hide and show user interface elements. W e can hide one or many elements on a page like this jQuery Primer in Html5:

$("h1" ).hide();

To show them, we simply call the show( ) method instead. We use the hide( ) method throughout this book to hide page sections that only need to appear when JavaScript is disabled, such as transcripts or other fallback content. html, val, and attr We use the html( )method to get and set the inner content of the specified element. Here, we’re setting the content between the opening and closing h1 tags to “Hello World. ” The v al ( ) method sets and retrieves the value from a form field. for jQuery Primer in Html5 It works exactly like the html( ) method. The attr( ) method lets us retrieve and set attributes on elements. append, prepend, and wrap The append( ) method adds a new child element after the existing elements. Given we have a simple form and an empty unordered list, like this:

<form id= "add" >
<label for= "task" >Task</label>
<input type= "text" id="task" >
<input type= "submit" value="Add" >
<ul id= "links" >

we can create new elements in the list by appending these new elements when we submit the form jQuery Primer in Html5.

$("#add" ).submit(function(event){
var new_element = $( "<li>" + $( "#email" ).val() + "</li>" );
$("#links" ).append(new_element);

The prepend() method works the same way as the append() method but inserts the new element before any of the existing ones. The wrap() method wraps the selected element with the element represented by the jQuery object you specify jQuery Primer in Html5.

$("h1" ).css( { "color" : "red" ,
"text-decoration" : "underline" }
var wrapper = $( "#message" ).wrap("<div><h2>Message</h2></div>" ).parent();

We can define these one at a time, but we can also use a JavaScript hash to assign many CSS rules to the element: However, it’s not a good idea to mix style with scripts. We can use jQuery’s addClass( ) and removeClass( ) methods to add and remove classes when certain events occur. W e can then associate styles with these classes. We can change the background on our form fields when they receive and lose focus by combining jQuery events and classes.

$("input" ).focus(function(event){
$(this).addClass("focused" );
$("input" ).blur(function(event){
$(this).removeClass("focused" );

Events to jQuery Primer in Html5
We often need to fire events when users interact with our page, and jQuery makes this very easy. In jQuery, many common events are simply methods on the jQuery object that take a function. For example, we can make all the links on a page with the class of popup open in a new window like this jQuery Primer in Html5:

var links = $( "#links a" );
 var address = $( this).attr('href' );

Inside our jQuery event handler, we can access the element we’re working with by using the this keyword. On line 3, we pass this to the jQuery function so we can call the attr( ) method on it to quickly retrieve the link’s destination address. We use the preventDefault( ) function to keep the original event from firing so it doesn’t interfere with what we’re doing. Bind Some events aren’t directly supported by jQuery, and we can use the bind( ) method to handle them. For example, when implementing the Drag and Drop part of the HTML5 specification, we need to cancel out the ondragover event. W e use the bind( ) like this jQuery Primer in Html5

target = $( "#droparea" )
target.bind('dragover' , function(event) {
if (event.preventDefault) event.preventDefault();
return false;

The Original Event on jQuery Primer in Html5

When we use any of the jQuery event functions like bind( ) or click( ), jQuery wraps the JavaScript event in its own object and copies only some of the properties across. Sometimes we need to get to the actual event so we can access those properties that didn’t get cloned. jQuery events give us access to the original event with the appropriately named originalEvent property. W e can access the data property of the onmessage event like this jQuery Primer in Html5:

$(window).bind("message" ,function(event){
var message_data = event.originalEvent.data;

Document Ready in jQuery Primer in Html5
The phrase “unobtrusive JavaScript” refers to JavaScript that’s kept completely separate from the content. Instead of adding onclick attribute butes to our HTML elements, we use event handlers like we just talked about in Section B.5, Events,We unobtrusively add behavior to our document, without modifying the document itself. Our HTML is not dependent on our users having JavaScript enabled. One drawback to this method is that JavaScript can’t “see” any of the elements in our document until they’ve been declared. We could include our JavaScript code in a script block at the bottom of the page after everything else has been rendered, but that isn’t reusable across pages. W e could wrap our code in JavaScript’s window.onLoad() event handler, but that event gets fired after all the content has loaded. This could cause a delay, meaning your users could be interacting with things before your events have been attached. W e need a way to add our events when the DOM is loaded but before it’s been displayed. jQuery’s document.ready function does exactly this, in a way that works across browsers. We use it like this jQuery Primer in Html5:

$(document).ready(function() {
alert("Hi! L am a popup that displays when the page loads" );

There’s a shorter, more compact version that we’ll be using throughout our code, which looks like this:

$(function() {
alert("Hi! L am a popup that displays when the page loads" );

We use this pattern in almost every example in this book so that we can easily, unobtrusively add fallback solutions to our projects. This is only a small sampling of what we can do with jQuery. Aside from the document manipulation features, jQuery provides methods for serializing forms and making Ajax requests and includes some utility functions that make looping and DOM traversal much easier. Once you become more comfortable with its use, you’ll no doubt find many more ways to use it in your projects to jQuery Primer in Html5.