Reputation: 25
I have a simple code, i want to hide a div
if user click on other div.container
or button
inside this div
here is my code
$('div, button').click(function(){
$('.div').toggle('hide');
})
div{
height: 200px;
width: 200px;
}
.container{
background: pink
}
.div{
background: blue
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button>Click</button>
</div>
<div class="div"></div>
its work fine when i click on container
div but its not working when i click on button, i know the porblem is that you fire a click two times.
but how to fix that
Upvotes: 2
Views: 60
Reputation: 1316
use below Jquery for the issue.
$('.container, button').click(function(){
$('.div').toggle(500);
return false;
})
Upvotes: 0
Reputation: 105
Please try this
$('div, button').click(function(){
$('.div').toggle('hide');
console.log("hello");
return false;
})
Upvotes: 0
Reputation: 207861
You can stop that by preventing the click event from bubbling up the DOM and triggering the click event on the parent with .stopPropagation():
$('div, button').click(function(e){
e.stopPropagation();
$('.div').toggle('hide');
})
div{
height: 200px;
width: 200px;
}
.container{
background: pink
}
.div{
background: blue
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button>Click</button>
</div>
<div class="div"></div>
Upvotes: 5