jQuery Events

jQuery is designed for event handling.

jQuery event functions

jQuery event handling methods are core functions in jQuery.

An event handler refers to a method that is called when certain events occur in HTML. The term 'triggered' (or 'triggered') by the event is often used.

jQuery code is usually placed in the event handling method of 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>

Try it yourself

In the above example, a function is called when the button's click event is triggered:

$("button").click(function() {  // some code... } )

This method hides all <p> elements:

$("p").hide();

Functions in a separate file

If your website contains many pages and you want your jQuery functions to be easy to maintain, then please put your jQuery functions in a separate .js file.

When we demonstrate jQuery in the tutorial, we will directly add the function to the <head> section. However, it is better to put them in a separate file, like this (referencing the file through 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 Conflict

jQuery uses the $ symbol as a shorthand for jQuery.

Functions in some other JavaScript libraries (such as Prototype) also use the $ symbol.

jQuery uses a method named noConflict() to solve this problem.

var jq=jQuery.noConflict(), which helps you use your own name (such as jq) instead of the $ symbol.

Try it yourself

Conclusion

Since jQuery is specifically designed to handle HTML events, it is more appropriate and easier to maintain your code when you follow the following principles:

  • Place all jQuery code in the event handler
  • Place all event handler functions in the document ready event handler
  • Place jQuery code in a separate .js file
  • If there is a name conflict, rename the jQuery library

jQuery Events

Below are some examples of jQuery event methods:

Event Functions Bind function to
$(document).ready(function) Bind a function to the document's ready event (when the document is fully loaded)
$(selector).click(function) Trigger or bind a function to the click event of the selected element
$(selector).dblclick(function) Trigger or bind a function to the double-click event of the selected element
$(selector).focus(function) Trigger or bind a function to the focus event of the selected element
$(selector).mouseover(function) Trigger or bind a function to the mouseover event of the selected element

For a complete reference manual, please visit our jQuery Event Reference Manual.