Events

We often need to fire events when users interact with our page, and jQuery makes this very easy. In jQuery, many common events are simply methods on the jQuery object that take a function. For example, we can make all the links on a page with the class of popup open in a new window, like this:

jqueryprimer/popup.html
Line 1 
var​ links = $(​"a.popup"​);
links.click(​function​(event){
var​ address = $(this).attr(​'href'​);
event.preventDefault();
window.open(address);
});

Inside our jQuery event handler, we can access the element we’re working with by using the this keyword. On line 3, we pass this to the jQuery function so we can call the attr method on it to quickly retrieve the link’s destination address.

We use the preventDefault ...

Get HTML5 and CSS3, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.