jQuery Events

jQuery Events: Learn what is jQuery event, its syntax, frequently used jQuery events, etc.
Submitted by Pratishtha Saxena, on September 01, 2022

In simple words, events can be understood as a result of some action that when gets triggered executes some custom functions declared within. Events can be anything that a user does on the document. It can be a click, checkbox selection, pressing a key on the keyboard, etc. anything. We can define some functionality when any of the events occurs. These custom-defined functions are often known as Event Handlers.

The event handler gets fired when an event occurs. The basic syntax of writing an event with and without the function is as follows.

Syntax:

$('selector').event();
$('selector').event(function(){});

Frequently used jQuery events

Some of the frequently used jQuery events are listed below.

  • click
  • dblclick
  • hover
  • keypress
  • keydown
  • keyup
  • mousedown
  • mouseup
  • focusin
  • load
  • resize
  • scroll
  • submit
  • change
  • select
  • blur
  • unload
  • ready

Amongst the above-mentioned events, let's discuss some of the important events for basic knowledge.

Click Event Method

This method detects the click where it is attached. If the element, attached to it, gets clicked then the function following it gets fired.

Syntax:

$('selector').click(function(){});

Example to demonstrate jQuery click event

$(document).ready(function () {
  $('#button1').click(function () {
    $('#myDiv').removeClass();
  });
});

Hover Event Method

The hover method gets triggered when the mouse cursor hovers over the targeted element. Hovering means when the cursor moves on an element. It takes in two parameters - mouseenter() and mouseleave(). Different functionalities can be assigned when a mouse cursor enters a specific area and when it leaves.

Syntax:

$('selector').hover(function(){});

Example to demonstrate jQuery hover event

$("#myHeading").hover(function () {
	alert("Mouse Move Over Element");
},
function () {
	alert("Mouse Leave");
});

KeyPress Event Method

When a key is pressed on the keyboard then this method gets triggered and hence fires the event handler attached to it. We can also dive into very specifics of the key press event, i.e., keyup and keydown.

Syntax:

$("selector").keypress(function(){});

Example to demonstrate jQuery keypress event

$(document).ready(function () {
  $("#myInput").keypress(function () {
    alert('Key is pressed!!');
  });
});

Similarly, there are a lot of event methods that have different functionalities. These methods are one of the important properties of jQuery which makes things a lot easier to work on. A long code can be compressed into a single line using these events and event handlers.





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.