Reputation: 21
In the following example, if you click the link, it displays the div
element.
How can I hide the div
when you click beyond the boundaries of the block or mouse across the border?
$(document).ready(function () {
$('a').click(function () {
$('.bg').css({'display': 'block'});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">Click</a>
<div style="background: #222; display:none" class="bg">Trololo</div>
Upvotes: 0
Views: 498
Reputation:
To hide the element once you've clicked anywhere in the document other than the link or the div, you have to monitor the click event for the document, then compare the clicked element against the link and the div, then check if the div is visible. If those conditions are all met then show the div.
To hide the element once you've "moused out" of the div, use jQuery.mouseout()
.
$(document).ready(function(){
var bg = $('.bg'), a = $('a');
a.click(function(){
bg.toggle();
});
$(document).click(function(e){
if(!a.is(e.target) && !bg.is(e.target) && bg.is(':visible')) {
bg.hide();
}
})
bg.mouseout(function(){
bg.hide();
})
});
.bg {
background: #222; color: #fff; line-height: 50px;
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">Click</a>
<div class="bg" style="display:none">Trololo</div>
Upvotes: 1
Reputation: 2475
Check out this fiddle http://jsfiddle.net/k0r5bh0t/
$(document).ready(function () {
$('a').click(function () {
$('.bg').css({
'display': 'block'
});
});
$(document).click(function(e){
if(e.target.id !='myBg' && e.target.id !='clickme'){
$('.bg').hide();
}
})
});
I have added ID to click me button and div which needs to be hidden. This should work
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<div class="col-sm-12"> <a href="#" id="clickme">Click</a>
<div style="background: #222" class="bg" id="myBg">Trololo</div>
</div>
Upvotes: 1
Reputation: 616
$(document).ready(function () {
$('a').click(function () {
$('.bg').show();
});
$('.bg').mouseout(function () {
$(this).hide();
});
});
This hides ".bg" when the mouse moves out of the black box. No clicking required.
Upvotes: 0