ptg16476052
Modifying Styles on the Page 505
18
The if statement tests whether the href attribute of the link starts with “http.” The other
tests in the if statement are checks that prevent the substring method from raising an
error if the URL is not present or is too short. If the URL does start with “http,” I open a
new window for that URL and prevent the default action. If it doesn’t, the default action
is allowed to continue. Instead of adding special classes to external links on the page or
using the onclick attribute for each of them to open new windows, I just used jQuery’s
selector functionality and a bit of programming to take care of it for me.
If you can’t get the previous script to work correctly, make sure
that the if statement is all on one line: if (null != this.href
&& this.href.length > 4 && this.href.substring(0,
4) == "http") {. Some browsers don’t like whitespace in the
middle of if statements.
CAUTION
jQuery provides methods for binding most events to jQuery objects. For more a full list
of events jQuery supports, see http://api.jquery.com/bind/.
Modifying Styles on the Page
Another powerful feature of jQuery is that it enables you to modify styles on the page
on-the-fly. jQuery enables you to modify the page styles indirectly through convenience
methods that hide and show elements, for example, and enables you to change styles
directly.
Hiding and Showing Elements
For example, you can hide and show elements easily based on activity by the user. Here’s
a sample page tha t swaps out two elements whenever they are clicked :
<!DOCTYPE html>