How to prevent click event in active class inside another click event using jQuery

I have several elements that got the .active class by clicking on them. Now I don’t need any clicks in any .active class. I have many click functions, which makes the active element. Thus, to prevent clicking on active classes, I wrote a prevent function in another place and call them inside each click function. But that did not work.

 $('body').on('click', '#one', function() { $(this).addClass('active'); // do something more noClickOnActive(); }); $('body').on('click', '#two', function() { $(this).addClass('active'); // do something more noClickOnActive(); }); function noClickOnActive() { $('body').on('click', '.content.active', function(event) { event.preventDefault() event.stopPropagation(); }); }; 

How to make it work?

Script work

+5
source share
3 answers

use below code. with the jquery hasClass () function you can check if a class has a class or not. it returns true / false.

Demo

  $('body').on('click', '#one', function() { if($(this).hasClass('active')){ return false; } $(this).addClass('active'); alert('clicked'); }); 
+3
source

Event handlers work in the order in which they are registered. Therefore, you may need to include this default event in the active class at the beginning of all other click events.

 $('body').on('click', '.content.active', function(event) { event.preventDefault() event.stopPropagation(); }); //Other event handlers code must be below 

Else binds the event to .content and checks for the presence of a class

  $('body').on('click', '.content', function(event) { if($(this).hasClass("active")) { event.preventDefault() event.stopPropagation(); } else { $(this).addClass("active"); } }); 
 .content { display: inline-block; border: 1px solid yellow; margin-right: 10px; padding: 5px; } .content:hover { cursor: pointer; } .content.active { background: yellow; cursor: inherit; } 
 <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <div class="content" id="one"> <p>Click Me</p> </div> <div class="content" id="two"> <p>Another Click Me</p> </div> 
+2
source

If a click is a problem, it means that some actions are tied to it. Would remove an action from an element to solve the problem? As with clicking, set the href link to "".

Or just put the if statement in your inputs and links. If you have few, this should not be a difficult task.

+1
source

All Articles