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
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.
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').
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');
});
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With