Enable and Disable Event from element with jQuery

jQuery not only allows us to attach event handlers on the element and it also allows us to take control of the flow of the events.

You can enable and disable an event whenever you want in your script.

When it’s required?

Enabling and disabling events becomes handy in various scenarios:

  1. No Longer Needed: There are situations when an event was initially attached to an element, but later in the script, it becomes unnecessary. In such cases, disabling the event can prevent unwanted behavior.
  2. Conditional Enabling: You may want to enable an event based on specific conditions. For example, on registration pages, websites often require users to agree to terms and conditions before enabling the “Submit” button.

To achieve event enablement and disabling, jQuery provides the on() and off() methods. These methods are instrumental in attaching and detaching event handlers from elements, giving you precise control over event behavior.

In this tutorial, I will show how to use the on() and off() methods effectively, along with a practical example.

Enable and Disable Event from element with jQuery


Table of Content

  1. The off() Method: Disabling Event Handlers
  2. The on() Method: Attaching Event Handlers
  3. Example: Enabling and Disabling Events with on() and off()
  4. Demo
  5. Conclusion

1. The off() Method: Disabling Event Handlers

The off() method in jQuery is a powerful tool that allows you to remove event handlers from specified elements, effectively disabling the associated events. This method comes in handy when you no longer want an element to respond to a particular event.

Syntax –

$(selector).off ( event );

Here, selector refers to the element from which you want to remove the event handler, and event is the specific event you wish to disable.

Example

In the example, I use the off() method to remove event handlers from specific elements.

  1. The first line of code removes the click event from all paragraph elements (<p>). After executing this code, any click on a paragraph element will no longer trigger the associated event handler.
  2. The second line of code removes the change event from the textbox with the ID "txt_username". As a result, the event handler attached to this textbox will no longer respond to changes made to its content.
$(document).ready(function(){
     // Remove click event from all paragraph elements
     $("p").off( 'click' ); 

     // Remove chanage event from Textbox id="txt_username"
     $( "#txt_username" ).off('change'); 

});

2. The on() Method: Attaching Event Handlers

In contrast to the off() method, the on() method in jQuery allows you to attach event handlers to selected elements, enabling them to respond to specific events when triggered.

Syntax –

$( selector ).on(event, function);

Here, selector represents the element(s) to which you want to attach the event handler. The event parameter is the name of the event you wish to handle (e.g., ‘click’, ‘keyup’, ‘mouseover’). The function parameter is the JavaScript function that will be executed when the specified event occurs.

Example

In the example, I use the on() method to attach event handlers to specific elements:

  1. The first line $("p").on('click', function(){ ... }); attaches a click event handler to all paragraph elements (<p> tags). When any paragraph is clicked, the associated anonymous function will execute, printing “paragraph click” to the console.
  2. The second line $("#txt_username").on('keyup', usernameChange); attaches a keyup event handler to the textbox with the ID "txt_username". Whenever a key is released while typing in the textbox, the usernameChange() function will be called, printing the current value of the textbox to the console.
$(document).ready(function(){
     // Attach click event to all paragraph elements
     $("p").on( 'click',function(){
          console.log('paragraph click');
     } ); 

     // Attach keyup event to Textbox id="txt_username"
     $( "#txt_username" ).on('keyup',usernameChange); 

});

function usernameChange(){
     var value = $(this).val();
     console.log(value);
}

3. Example: Enabling and Disabling Events with on() and off()

In this example, HTML form consisting of a Textbox and a Button, along with a message to indicate that the age should be greater than 18. Using jQuery, to manipulate event handling to enable or disable the Button click event based on the user input.

Event Manipulation Logic:

  1. When the user enters a value in the Textbox, a change event is triggered.
  2. Extract the age value entered by the user and convert it to a number using Number().
  3. If the entered age is greater than 18, enable the click event for the Button using the on() method. The click event is now associated with the printAge() function.
  4. Conversely, if the entered age is less than or equal to 18, disable the click event for the Button using the off() method. This ensures that the Button will not respond to clicks.

This example demonstrates how the use both on() and off() methods together to control event behavior dynamically. Depending on the user input, adjust the event handling behavior, creating a more customized and interactive experience for the user.

<input type='text' id='txt_age' placeholder='Enter your Age'>
<input type='button' id='submit' value='Submit'><br/>
<span style='color: red;'>Age should be greater than 18</span>
<div>Your Age: <span id='age'></span></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){

    $("#txt_age").change(function(){
         var age = Number( $("#txt_age").val() );
         if(age > 18){

              // Attach click event
              $("#submit").on('click',printAge);
         }else{

              // Remove click event
              $("#submit").off("click");
         }
    });
 
});

// Display Age
function printAge(){
    var age = $("#txt_age").val();
    $("#age").text(age);
}
</script>

4. Demo

View Demo


5. Conclusion

I showed how you can enable disable an event handler from the element. By this, you can restrict when the event will trigger or disable.

If you are using AJAX for saving data and want the user only able to click once on the button, in this case, you can either remove the click event or add a disabled attribute.

If you found this tutorial helpful then don't forget to share.

Leave a Comment