How to use disable click event in jQuery
In this article, you will learn about how to use disable click events in jQuery.
jQuery is a lightweight and feature-rich JavaScript library. You can do a lot more things and bring interactivity to your webpage. The purpose of jQuery is to write less and do more. That means you can do a lot more things by writing less code. Disabling an event by using jQuery is one of them.
In jQuery, you can create a button event for example when a button is clicked an alert message will show in the display. Similarly, you can disable this functionality by using jQuery. To show, the message jQuery provides the on() method and to disable this event you will get the off() method. Let’s see the syntax of using the off() method in jQuery.
$('#button').off('click');
You can see that the syntax is very simple and easy to use. Let’s see an example of it to understand things more clearly in the below section
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>jQuery disable</title>
</head>
<body>
<div class="element">
<h1>Learn jQuery Disable Element</h1>
<button id="clickMe">Click me</button>
<button id="disableMe">Disable me</button>
</div>
<script src="<https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js>" ></script>
<script src="app.js"></script>
</body>
</html>
Here, we simply take two buttons one is for the click event and another is for disabling the click event and linking the jQuery file from CDN, and linking our own app.js file. You download jQuery file and link on your local machine but to make things simple we are doing like this.
JavaScript
$(document).ready(function(){
$('#disableMe').on('click',function(){
$('#clickMe').off('click');
});
$('#clickMe').on('click',function(){
alert('Hello! I am from Click Me');
});
});
Here, we simply write the functionality to make things happen and using on() and off() that we have discussed in the earlier section of this article. Let’s see the output below:
Output
You can see that when we have clicked on the click me button an alert message has been shown. Now let’s try clicking disable me button first and then click on the click me button and see if the alert message shows up or not.
Now, our click me button is disabled and no alert message has been shown at this time. Because we disable the functionality by clicking disable me button. That means we successfully implement our functionality and to give it a better look we used some CSS styles but this is not important. You can give styles on your own interest.