Reputation: 2738
I want to disable clicks on certain elements within a parent div with jQuery. How can it be done?
My approach was to try to exclude it from selection:
$('.wrap1 :not(.wrap3 li)').on("click", function() {
alert(1);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap1">
<div class="wrap2">
<p>Some text</p>
<ul>
<li>list 1</li>
<li>list 2</li>
<li>list 3</li>
</ul>
</div>
<div class="wrap3">
<ul>
<li>Should not be clickable</li>
</ul>
</div>
</div>
The result that I'm looking for is: if I click inside the wrap1
div, it should prompt me the alert box, except when I click inside the wrap3
div.
What am I missing here?
Upvotes: 1
Views: 55
Reputation: 4101
there is no need of function
keyword in arrow function
$('.wrap1 :not(.wrap3 li)').on("click", e => {
e.stopPropagation();
alert(1);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap1">
<div class="wrap2">
<p>Some text</p>
<ul>
<li>list 1</li>
<li>list 2</li>
<li>list 3</li>
</ul>
</div>
<div class="wrap3">
<ul>
<li>Should not be clickable</li>
</ul>
</div>
</div>
Upvotes: 1
Reputation: 11
Use event.stopPropagation()
<script>
$('.wrap1').on("click", function(){
alert(1);
});
$(".wrap3").on("click", function(event){
// This will stop propagation of the event to parent element.
event.stopPropagation();
});
</script>
Upvotes: 1
Reputation: 89254
Your best bet is checking the event's target.
$('.wrap1').on("click", function(e){
if(!$(e.target).is(".wrap3, .wrap3 *")){
alert(1);
}
})
$('.wrap1').on("click", function(e){
if(!$(e.target).is(".wrap3, .wrap3 *")){
alert(1);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap1">
<div class="wrap2">
<p>Some text</p>
<ul>
<li>list 1</li>
<li>list 2</li>
<li>list 3</li>
</ul>
</div>
<div class="wrap3">
<div style="border: 1px solid red;">
ABC
<div style="background-color:dodgerblue;">
CDE
</div>
</div>
<ul>
<li>Should not be clickable</li>
</ul>
</div>
</div>
Upvotes: 1
Reputation: 24638
This should do it!
$('.wrap1').on("click", function(e) {
if( $(e.target).is('.wrap3 li') ) { return false; }
alert(1);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap1">
<div class="wrap2">
<p>Some text</p>
<ul>
<li>list 1</li>
<li>list 2</li>
<li>list 3</li>
</ul>
</div>
<div class="wrap3">
<ul>
<li>Should not be clickable</li>
</ul>
</div>
</div>
Upvotes: 0
Reputation: 64657
Not sure why your way doesn't work, but this does:
$('.wrap1 li').not('.wrap3 li').on("click", (e) => {
e.stopPropagation();
alert(1);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap1">
<div class="wrap2">
<p>Some text</p>
<ul>
<li>list 1</li>
<li>list 2</li>
<li>list 3</li>
</ul>
</div>
<div class="wrap3">
<ul>
<li>Should not be clickable</li>
</ul>
</div>
</div>
Upvotes: 1