jQuery Events

jQuery Events

jQuery is tailor-made to respond to "events" happening on your HTML page.

An event represents the precise moment when something interactive happens.

Examples include a user clicking a button, moving a mouse over an image, or pressing a key.


Common DOM Events

Events are categorized by the type of user interaction that triggers them.

Here is a quick list of the most common events you will use:


The click() Method

The click() method attaches an event handler function to an HTML element.

The code inside the function only executes when the user clicks on the HTML element.

Click Event Example:

$("p").click(function(){
  $(this).hide();
});

The dblclick() Method

The dblclick() method attaches an event handler function to an HTML element.

The code executes only when the user double-clicks on the HTML element.

Double Click Event Example:

$("p").dblclick(function(){
  $(this).hide();
});

Mouse Enter and Mouse Leave

The mouseenter() method triggers when the mouse pointer enters the element's space.

The mouseleave() method triggers when the mouse pointer leaves the element's space.

Mouse Enter Example:

$("#target").mouseenter(function(){
  alert("You hovered over the target!");
});

The hover() Method

The hover() method is extremely useful because it combines mouseenter() and mouseleave().

It takes two separate functions inside of it.

The first function executes when the mouse enters, and the second when the mouse leaves.

Hover Event Example:

$("#p1").hover(
  function(){
    console.log("Mouse entered the paragraph.");
  },
  function(){
    console.log("Mouse left the paragraph.");
  }
);

The on() Method (Multiple Events)

The on() method attaches one or more event handlers for the selected elements.

It is the modern and preferred way to attach events in jQuery.

The on() Method Example:

$("p").on("click", function(){
  $(this).hide();
});

Exercise

?

Which jQuery method combines both the mouseenter and mouseleave events into one?