onclick function jquery

Understand the onclick function in jQuery

If you are working with web development or programming, you might have heard about jQuery. It is a popular JavaScript library that simplifies the complex task of writing JavaScript code. One of the useful features of jQuery is the onclick function. It allows you to assign a function to an HTML element's click event.

Let's understand how to use the onclick function in jQuery to add interactivity to your website.

Syntax of onclick function in jQuery

The syntax of the onclick function in jQuery is straightforward. You can select an HTML element using jQuery selectors and attach the onclick function to it. Here is an example:

  alert("Button clicked!");

In this example, we have selected the HTML element with id "myButton" using the jQuery selector "$("#myButton")". We have then attached the onclick function to it using the click() method. Inside the click() method, we have defined an anonymous function that displays an alert message when the button is clicked.

Multiple ways to use onclick function in jQuery

There are multiple ways to use the onclick function in jQuery. Apart from using the click() method, you can also use the bind() method or the on() method. Here is how you can use these methods:

  • bind() method:
$("#myButton").bind("click", function(){
  alert("Button clicked!");
  • on() method:
$("#myButton").on("click", function(){
  alert("Button clicked!");

Both the bind() method and the on() method work similarly to the click() method. However, they provide additional functionalities like handling multiple events and dynamic elements.


The onclick function in jQuery is a powerful tool that adds interactivity to your website. With the help of jQuery selectors and event handling methods like click(), bind() and on(), you can easily attach functions to HTML elements' click events.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]