02.06.2013 Views

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS<br />

After execution, upon clicking the paragraph with ID bar, the three messages are logged in<br />

succession on consequent clicks.<br />

Next, toggle the visibility of the paragraph with ID bar with the following code:<br />

$("#bar").toggle();<br />

Firing this function hides the paragraph. Firing it again brings it back. By adding the duration as the<br />

first argument, the method will animate the element as it’s hidden or shown:<br />

$("#bar").toggle(2000);<br />

Last, a Boolean flag can be passed to determine whether all elements should be shown or hidden:<br />

$("#bar").toggle(true); // all elements will be shown<br />

$("#bar").toggle(false); // all elements will be hidden<br />

.trigger()<br />

To trigger an event, the .trigger() method is used. This method accepts an event to trigger <strong>and</strong> an<br />

optional array of arguments to be passed to the h<strong>and</strong>ler.<br />

Bind a h<strong>and</strong>ler to the paragraph with ID bar, <strong>and</strong> trigger it using the following code:<br />

$("#bar")<br />

.bind("click", function(){<br />

console.log("Clicked!");<br />

})<br />

.trigger("click");<br />

To pass additional data, modify the code as follows:<br />

// create a variable<br />

var note = "I was triggered!";<br />

$("#bar")<br />

.bind("click", function(event, msg){ // allow a 2nd argument<br />

// If no msg variable is passed, a default message<br />

var log = msg || "I was clicked!";<br />

console.log(log);<br />

})<br />

.trigger("click", [ note ]); // array passed in square brackets<br />

This outputs the message stored in the note variable to the console.<br />

Shortcut Event Methods<br />

Every event has a shortcut method that accepts the h<strong>and</strong>ler function as an argument. If passed without<br />

an argument, it calls .trigger() for its event type.<br />

The available shortcut functions are .blur(), .focus(), .focusin(), .focusout(), .load(), .resize(),<br />

.scroll(), .unload(), .click(), .dblclick(), .mousedown(), .mouseup(), .mousemove(), .mouseover(),<br />

.mouseout(), .mouseenter(), .mouseleave(), .change(), .select(), .submit(), .keydown(), .keypress(),<br />

.keyup(), <strong>and</strong> .error().<br />

77

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!