Beginning jQuery by Jack Franklin & Russ Ferguson

Beginning jQuery by Jack Franklin & Russ Ferguson

Author:Jack Franklin & Russ Ferguson
Language: eng
Format: epub
Publisher: Apress, Berkeley, CA


That link is within a div, and as a simplified example, suppose that when the link is clicked, you’d like the background of the div to change to blue, and then nothing more to happen. The first attempt at this would probably look like so:

$(function() {

$("a").on("click", function() {

$("div").css("background", "blue");

});

});

If you try that in your browser, you will see the div turn blue for a split second before you are taken to the Apress web site. So, while it is executing your code, it’s then immediately whisking the user off to another site, rendering your code useless.

On the event object, along with stopPropagation() , there’s also preventDefault(), and you can probably figure out what that one does. You use it just as you did with stopPropagation()—pass in an event object to the event handler and then call preventDefault() on that object:

$(function() {

$("a").on("click", function(event) {

event.preventDefault();

$("div").css("background", "blue");

});

});



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.