The most common event that you have encountered in previous examples is the Document Ready Event. This event is to prevent any jQuery code from running before the document is loaded completely. The syntax is:
$(document).ready(function(){ // jQuery code... });
Table 5.1 below shows some common events.
Mouse Events | Keyboard Events | Form Events | Document Events |
---|---|---|---|
click | keypress | focus | load |
dblclick | keydown | blur | unload |
mouseenter | keyup | change | resize |
mouseleave | select | scroll | |
mouseup | submit | ready | |
mousedown | focusin | ||
hover |
To assign an event to an an HTML element, we use the following syntax:
$("element").event();
We also need to attach an event handler function to the element so that it executes some actions after the event is triggered(or fired).
The syntax is:
$("element").event(function(){ jQuery code that execute some actions });
The jQuery function is executed when the user clicks on an HTML element.
In this example, when the user clicks the button, all the paragraphs will disappear.
<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ $("button").click(function(){ $("p").hide(); }); }); </script> </head> <body> <h2> jQuery Event</h2> <p>Paragraph 1.</p> <p>Paragraph 2</p> <p>Paragraph 3</p> <button>Click to hide paragraphs</button> </body> </html>
Paragraph 1.
Paragraph 2
Paragraph 3
In this example, when the user double-clicks the button, all the paragraphs will disappear.
The jQuery function is executed when the user double-clicks on an HTML element.
<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ $("button").dblclick(function(){ $("p").hide(); }); }); </script> </head> <body> <h2> jQuery Event</h2> <p>Paragraph 1.</p> <p>Paragraph 2</p> <p>Paragraph 3</p> <button>Click to hide paragraphs</button> </body> </html>
Paragraph 1.
Paragraph 2
Paragraph 3
The jQuery function is executed when the mouse pointer enters an HTML element.
<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ $("h3").mouseenter(function(){ $("h3").hide(); }); }); </script> </head> <body> <h3> Drag the mouse over me to make me disappear</h3> <p>Paragraph 1.</p> <p>Paragraph 2</p> </body> </html>
Paragraph 1.
Paragraph 2
The jQuery function is executed when the mouse pointer leaves an HTML element.
<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ $("h3").mouseenter(function(){ alert("You are leaving me!"); }); }); </script> </head> <body> <h3> Don't Leave Me</h3> <p>Paragraph 1.</p> <p>Paragraph 2</p> </body> </html>
Paragraph 1.
Paragraph 2
Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy