I have .main
that contain a list of dynamic content that can be added on the fly. The .main
can also be disabled with .disable
class. When it's disabled, I don't want all the content items to be clicked.
You can see below that I am using a hack to detect .disable
class after .main
being clicked. Is there a way to structure the CSS selector for jQuery to avoid picking up children DOMs event if parent has certain class? Maybe some kind of .main:not(.disable)
but I couldn't figure out how.
Code: http://jsfiddle.net/qhoc/99rjU/
HTML:
<div class="main">
<div class="state">Enabled</div>
<ul>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
</ul>
</div>
<a class="btn" href="#">
Toggle State
</a>
Javascript:
$('.btn').on('click', function() {
if ($('.main').hasClass('disable')) {
$('.main').toggleClass('disable');
$('.state').text('Enabled');
} else {
$('.main').toggleClass('disable');
$('.state').text('Disabled');
}
});
$('.main').on('click', ' ul li', function() {
/* This is a hack
if ($('.main').hasClass('disable'))
return;
*/
alert('Item is clicked');
});
I was thinking of other unclean alternatives :
Do whole body
click event like this $('body').on('click', '.main:not(.disable) ul li', function()
but this one is very ugly! It has to scan the whole body on each click
Unbind li
click event each time a
is trigger to call disable
. But is this an optimal or best practice to do so?
UPDATE 1 :
So actually in my project I only want to disable the a
in the list. Since there are other buttons
and divs
that I still want to trigger event. However, look like using this won't work
.disable li a
{
pointer-events: none;
}
Here is the link for this http://jsfiddle.net/qhoc/99rjU/2/
Look like this is still experimental and won't work on anchor tag??
https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
Well you could disable all click event's on the div when it has the class .disable
with css:
.disable
{
pointer-events: none;
}
This way nothing inside the div is clickable.
For IE it is somehow harder, as IE 10 and below doesn't support pointer-events
. However a great article has been written on how to bypass this with a layer function: http://www.vinylfox.com/forwarding-mouse-events-through-layers/
I hope this is what you mean.
$('.btn').on('click', function() {
var main = $('.main');
$('.state').text(main.hasClass('disable') ? 'Enabled' : 'Disabled');
main.toggleClass('disable');
});
$('.main').on('click', 'li', function(e) {
if ($(this).parents('.main.disable').length) {
// actually this is similar to your alternative#1
return;
}
alert('Item is clicked');
});
What about this?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.