jQuery Events Handling

What is Event?

Events are actions that can be used in the application. The events can be bind using jquery methods like .on, .bind,etc.,. Below are the few examples for events

  • Mouse click
  • Mouse over on an Element
  • Key Enter
  • An HTML form submission

When these events are triggered, we can use our own custom function to handle the event. These custom functions called as Event Handlers.

Types of Events:

jQuery provides a number of  shorthand Event methods and each corresponds to a DOM event. 

Event Name Shorthand Method
click .click()
keydown .keydown()
keydown .keypress()
keyup .keyup()
mouseover .mouseover()
mouseout .mouseout()
mouseenter .mouseenter()
mouseleave .mouseleave()
scroll .scroll()
focus .focus()
blur .blur()
resize .resize()

Binding Event Handler :

Let us discuss about event handling with simple examples.

Example 1: Simple event binding

$( “div” ).on( “click”, function() {
alert( “div clicked by user” );
});

Explanation :

In the above example, the method is to handle the click event for the div. If user click the div, then click function will automatically triggered
and alert dialog box will appear with the message “div clicked by user”.

Example 2: Handling more than one events

We can handle more than one event in the single function as shown below. 

$( “div” ).on( “mouseenter mouseleave”, function() {
alert( “User using mouse-enter/leave” );
});

Explanation :

The event will trigger after user mouseover/mouseleave on the div.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.