Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent click event on a active class inside another click event with jQuery [closed]

Tags:

jquery

I have several items which has been gotten .active class by clicking on them. Now, I need no click events will happened at any .active class. I have many click functions which makes the item active. So, for preventing click on the active classes, I wrote the prevent function at another place and call them inside every click functions. But, it didn't 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 working?

Fiddle work

like image 304
user1896653 Avatar asked Apr 08 '15 17:04

user1896653


People also ask

How do I prevent a parent's onclick event from firing when a child is clicked?

Use stopPropagation method, see an example: As said by jQuery Docs: stopPropagation method prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

How do you add active class on click event?

In Bootstrap 4, Javascript or jQuery events are used to add active class on click event in custom list group. Syntax: $(document). ready(function() { $('selector').


2 Answers

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

DEMO

 $('body').on('click', '#one', function() {  
   if($(this).hasClass('active')){
      return false;
   }
   $(this).addClass('active');
    alert('clicked');
 });
like image 151
Nishit Maheta Avatar answered Oct 26 '22 19:10

Nishit Maheta


Event handlers work in the order they are registered. So you may need to put this prevent default event on active class at the top of all other click events.

$('body').on('click', '.content.active', function(event) {  
    event.preventDefault()
    event.stopPropagation();
}); 

//Other event handlers code must be below

Else bind the event to .content and check for class there

 $('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>
like image 20
mohamedrias Avatar answered Oct 26 '22 19:10

mohamedrias