Handling Events
Course- Javascript >
You can attach event handlers to elements or collections of elements a number of ways in jQuery. First, you can add event handlers directly, like this:
$("a").click(function() { // execute this code when any anchor element is clicked });
Alternatively, you can use a named function, like this:
function hello() { alert("Hello from jQuery"); } $("a").click(hello);
In these two examples the function will be executed when an anchor is clicked. Some other common events you might use in jQuery include blur, focus, hover, keypress, change, mousemove, resize, scroll, submit, and select. To help you add multiple event handlers, jQuery wraps the attachEvent and addEventListener JavaScript methods in a cross-browser way:
$("a").on('click', hello);
The on() method can be used to attach handlers both to elements already present in the original HTML page and to elements that have been dynamically added to the DOM.
The on() method was introduced in jQuery 1.7 and is the recommended replacement for several previous event-handling methods, including bind(), delegate(), and live(). See the jQuery documentation for complete details.