<%response.buffer=true%> <% yere = year(date()) Response.Expires = 0 %> Advanced Forms
<Working with jQuery >
  spacerspacer

Applied jQuery

Now that we have some jQuery fundamentals under our belt, lets work our way toward applying jQuery.

Attribute Manipulation Methods: Once we have our selections, we can inspect and manipulate the attributes on the selections with jQuery's attr() methods.

In this example use we set all of the <a> tags to be target="_blank" and open into new windows from our page:

$("a").attr("target","_blank");

We would place the above code into an anonymous function inside $("document").ready().

In the next example we'll use the attr() method to change multiple attributes of an image:

$("#myImg").attr({

src: "myFlower.jpg",
border:"1",

alt:"My Flower Pic "

})

When we change an image we may wish to switch several attributes. We can do this by using the extra curly brace then comma separate our name/value pairs in JavaScript object notation.

Here are the attr() methods:

Attribute Method Purpose Example Returns
.attr(name)
Accesses properties on the first matched element. If no match, returns undefined.
var mySrc = $("#myImg").attr("src")
Copies the value in the src attribute into a variable
.attr(key,value)
Sets a single property to a value on all elements
$("#myImg").attr(src, "myPic.jpg")
Changes the src attribute on an element with an id of myImg
.attr(properties)
Sets a series of attributes on all matched elements using object notation syntax
$("#myImg").attr({src: "myPic.jpg",alt:"myTitle"})
Changes the src and alt attribute of an element with an id of myImg
.removeAttr(name)
Removes named attribute from all elements
$("a").removeAttr("href")
Removes href attributes (links) from all <a> tags

CSS Methods: Working with CSS is so important that there are a whole set of methods we can use.

In this example we set all even list items to a background color of blue:

$("li:even").css("background-color","blue");

We could place the above code into an anonymous function inside $("document").ready().

In the next example we'll use the css() method to change multiple CSS properties on a div:

$("#myDiv").css({

background-color: "yellow",
border:"1 solid black"

})

Here are the css() methods:

CSS Method Purpose Example Returns
.css(name)
Returns the value for the named CSS property for the first matched element.
$("#myDiv").css("background-color")
Returns the background color of myDiv
.css(property,value)
Sets a single property to a value on all elements
$("#myDiv").css("background-color","red")
Changes the background color of myDiv to red
.css(properties)
Sets a series of attributes on all matched elements using object notation syntax

$("#myDiv").css({background-color:"yellow",
border:"1 solid black"})

Changes the src and alt attribute of an element with an id of myImg
.addClass(class)
Adds the specified class(es) to each of the elements
$("a").addClass("myClass")
Adds myClass to all <a> tags
.removeClass(class)
Removes the specified class(es) from each of the elements
$("a").removeClass("myClass")
Removes myClass from all <a> tags
.hasClass(class)
Returns true if class is present in at least one of the matched elements

if($("#myDiv").hasClass("myClass"))

{alert("it has myClass!");}

if myDiv element has myClass, pop an alert()
.toggleClass(class)
Adds or removes the specified class(es) on each of the elements
$("a").toggleClass("myClass")
Adds or removes (toggles) myClass on all <a> tags

CSS Positioning Methods: jQuery has several methods to get and set various positioning properties like position() which gets the top and left position in pixels relative to its offset parent of the first matched element:

var top = $("#myDiv").position().top;
var left = $("#myDiv").position().left;
alert("myDiv is currently " + top + " pixels from the top and " + left + " pixels from the left of the screen");

Many of jQuery's CSS positioning and sizing methods can be seen in the source of this demo from Joe Marini of lynda.com: css_sizing example

jQuery Events: Just as jQuery replaces traditional DOM manipulation with jQuery specific cross browser custom object methods, jQuery does the same for assigning (and unassigning) event handling code to events in a cross browser manner.

jQuery Event Helpers: jQuery provides several event 'helper' methods to simplify attaching event handling functions to common events such as click,blur,keypress,mouseover,mouseout and many others. Here's how to attach a function named myFunction to a click event:

$("#myDiv").click(myFunction);

Note the name of the function is not quoted above. Another helper function hover() accepts 2 functions, and toggles between them for a combination of mouseover/mouseout events:

$("#myDiv").hover(overFunction,outFunction);

A third helper function toggle() can roll through any number of functions on each click by turns:

$("#myDiv").toggle(click1Function,click2Function,click3Function);

Here's a demo of event helper methods

Multiple Event Handlers per Event: When we assign event handlers via the helper methods above we are usually only assigning one function to one event. However there are times that we want to assign (and de-assign) multiple event handling functions to an event.

jQuery uses a bind() and unbind() method to assign and unassign event handling functions. Using bind() and unbind() allow us to used multiple named (not anonymous) functions with events.

View the following binding example

jQuery Event Object: To interrogate or alter events and details of the target object of the events. For details view the jQuery Event object example

Special jQuery Methods: jQuery provides a couple of special event handling methods. One is the one() method which works like the click() method, but will fire one time only:

$("#myDiv").one(clickFunction);

jQuery Stripe & Hover: Here's an example that uses jQuery event methods to create a stripe & hover table

jQuery Events Test Bed: Our book provides a jQuery Events Test Bed

jQuery Effects: jQuery provides a set several built in effects to show, hide, fade in and out and slide elements. Most of the methods below have default time settings, which we can override:

Effect Method Purpose Example Returns
.show()
Adds the previously hidden element

$('#myDiv').show();

Makes previously invisible myDiv element appear
.hide()
Removes the selected elements from view - most elements must be previously hidden to use fadeIn(), etc.

$('#myDiv').hide();

Removes previously visible myDiv element
.toggle()
Adds or removes the selected elements from view

$('#myDiv').toggle();

Adds or Removes previously visible myDiv element
.fadeIn(ms)
Fades the previously hidden element into place in the doc
$('#myDiv').fadeIn(2000);
myDiv Element fades in to place and view over 2 seconds time
.fadeOut(ms)
Fades the previously visible element out of place in the doc
$('#myDiv').fadeOut(2000);
myDiv Element fades out of place and view over 2 seconds time
.slideDown(ms)
Slides Previously hidden element down and into view
$('#myDiv').slideDown(2000);
myDiv Element slides down and into place over 2 seconds time
.slideUp(ms)
Slides Previously visible element up and out of view
$('#myDiv').slideUp(2000);
myDiv Element slides up and out of view over 2 seconds time
.slideToggle(ms)
Slides elements up or down - great for menu navigation
$('#myDiv').slideToggle(2000);
myDiv Element slides down and into place or up and out of view over 2 seconds time
.animate(params,ms,easing)
Animates opacity, size, position and other CSS parameters from initial settings to new settings
$("#myDiv").animate({left: 500,width:"250px"})
myDiv Element slides to 500px to the left of it's current position and shrinks (or grows) to 250 pixels wide

Callbacks: All of the effects above allow a second (or in the case of animate() a final) optional parameter, which would be a function to run when the first method is complete. Here are a few examples, all of which make use of callback functions: fade , slide and animate

Q & A: A common problem aided by jQuery is easing the monotony of working through a traditional FAQ page. Instead of scrolling for miles on a long page, we can have jQuery use hide() fadeIn() and next() to open and close the individual FAQ. View page 227 of our book for details: One Page FAQ

jQuery Photo Galleries: Several of the effects above are used to build a 'plugin free' photo rotator in jQuery built by Joe Marini of lynda.com: jQuery Image Rotator

Here's a more complex photo gallery featured in a tutorial on page 248 of our book: jQuery Photo Gallery

jQuery Effects Test Bed: Our book also provides a jQuery Effects Test Bed

jQuery UI Library & Plugins: Next we'll be covering the jQuery UI Library which creates a range of pre-built tools we can use in our website without needing to build them from scratch!

Using jQuery & other APIs Simultaneously: jQuery and other APIs such as MooTools share a similar approach to the point that placing references to both libraries on a single page can cause errors.

jQuery uses the $ as a shortcut to speak to it's API. MooTools uses $$. In order to avoid a potential conflict, jQuery uses a method named noConflict():

<script type="text/javascript" src="jquery-1.3.js"></script>
<script type="text/javascript">
jQuery.noConflict(); //no conflict jquery
(function($) {
$('p').css('color','#ff0000');
})(jQuery);
</script>
<script type="text/javascript" src="moo1.2.js"></script>
<script type="text/javascript">
//MooTools code
window.addEvent('domready',function() {
$$('p').setStyle('border','1px solid #fc0');
});
</script>

The above sample code comes from a blog where developers discuss the merits of Using jQuery and MooTools together

Our Book's other Demos: Here are some other great demos from our book: Missing Manual jQuery Examples

   
Print this Page Back To Top

2000- <%=yere%> newMANIC INC, All rights reserved