How to Handle Button Click Event in jQuery

Shraddha Paghdar Feb 02, 2024
How to Handle Button Click Event in jQuery

In today’s post, we’ll learn about the button click event in jQuery.

Handle Button click Event in jQuery

jQuery has an integrated .click() approach that binds an event handler to the JavaScript click event or dispatches this event on an element.

Syntax:

.click(handler).click([eventData], handler)
  1. The handler is a function executed every time the event is triggered.
  2. The event data is an object containing data to be surpassed by the event handler.

This method is an abbreviation for .on("click", handler ) in the first two variants and .trigger( "click" ) in the third. The click event is sent to an element while the mouse pointer is over the element, and the mouse button is pressed and launched.

Any HTML element can receive this event. As the .click() method is just an abbreviation for .on("click", handler ), it can be separated with .off("click").

The click event is only dispatched after this exact series of events:

  1. The mouse button is pressed while the mouse pointer is over the element.
  2. The mouse button is released while the mouse pointer is over the element.

This is usually the desired sequence before performing an action. If this isn’t required, the mousedown or mouseup event might be more appropriate.

Let’s understand it with the following example:

<button id="btn">Hello World!</button>
$('#btn').click(() => {console.log('Click event fired')});

In the above example, we have defined the button element. The click event is dispatched, and the function is executed as soon as the button is clicked.

Attempt to run the above code snippet in any browser that supports jQuery. It’s going to display the beneath result:

Output:

Click event fired

View the demo here.

Shraddha Paghdar avatar Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn

Related Article - jQuery Event