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.