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.

60<br />

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

Add the class baz <strong>and</strong> remove the class foo from the second paragraph in the example page using<br />

the following code:<br />

$("p.foo").toggleClass("foo baz");<br />

Upon execution, the paragraph is modified <strong>and</strong> appears with the old class removed <strong>and</strong> the new one<br />

added (see Figure 2-17).<br />

Figure 2-17. The foo class is removed, <strong>and</strong> the baz class is added.<br />

To revert to the original class of foo <strong>and</strong> remove baz, select the paragraph, <strong>and</strong> apply .toggleClass()<br />

again:<br />

$("p.baz").toggleClass("foo baz");<br />

This results in the paragraph going back to having only one class: foo.<br />

.hasClass()<br />

The .hasClass() method works similarly to the .is() method in that it determines if a class exists on a<br />

selected element <strong>and</strong> then returns either true or false. This makes it ideal for callback functions.<br />

Check if the first paragraph has class foo, <strong>and</strong> conditionally output a message using the following:<br />

var msg = $("p:eq(1)").hasClass("foo") ? "Found!" : "Nope!";<br />

console.log("Class? "+msg);

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

Saved successfully!

Ooh no, something went wrong!