Thursday 28 April 2011

jQuery Events


jQuery is tailor made to handle events.

jQuery Event Functions

The jQuery event handling methods are core functions in jQuery.
Event handlers are method that are called when "something happens" in HTML. The term "triggered (or "fired") by an event" is often used. 
It is common to put jQuery code into event handler methods in the <head> section:

Example

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("p").hide();
  });
});
</script>
</head>

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
In the example above, a function is called when the click event for the button is triggered:
$("button").click(function() {..some code... } )
The method hides all <p> elements:
$("p").hide();

Functions In a Separate File

If your website contains a lot of pages, and you want your jQuery functions to be easy to maintain, put your jQuery functions in a separate .js file.
When we demonstrate jQuery here, the functions are added directly into the <head> section, However, sometimes it is preferable to place them in a separate file, like this (refer to the file with the src attribute):

Example

<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="my_jquery_functions.js"></script>
</head>


jQuery Name Conflicts

jQuery uses the $ sign as a shortcut for jQuery.
Some other JavaScript libraries also use the dollar sign for their functions.
The jQuery noConflict() method specifies a custom name (like jq), instead of using the dollar sign.


jQuery Events

Here are some examples of event methods in jQuery: 
Event MethodDescription
$(document).ready(function)  Binds a function to the ready event of a document
(when the document is finished loading)
$(selector).click(function)Triggers, or binds a function to the click event of selected elements
$(selector).dblclick(function)Triggers, or binds a function to the double click event of selected elements
$(selector).focus(function)Triggers, or binds a function to the focus event of selected elements
$(selector).mouseover(function)Triggers, or binds a function to the mouseover event of selected elements

No comments:

Post a Comment