Reputation: 135
Html
<div class="lang-currency-field">
<div class="lang-currency-links">links here</div>
</div>
jQuery
<script>
$('.lang-currency-button').click(function() {
$('.lang-currency-field').fadeIn();
});
$('.lang-currency-links').click(function() {
$('.lang-currency-field').fadeOut();
});
$('.lang-currency-field').outside('click', function(){
$('.lang-currency-field').fadeOut();
});
</script>
I've read many articles and forums here on stackoverflow but I can't sort this out for some reasons.
How can I close/fadeOut the lang-currency-field div by clicking somewhere on the page?
It closes fine when I click on one of the links but not when I actually click out of the div.
Could you help me please? Thank you.
Upvotes: 0
Views: 7534
Reputation: 532435
I would suggest a handler on the div that prevents event bubbling and then delegate the "outside" handler to the document. The handler on the div prevents clicks within the div, but not on a link from having the document-level handler close the div. Note: you'll need to be careful of other handlers for the page that they either allow clicks to bubble up to the document (if outside the div you're closing), they take care of closing the div as well, or they take you to another page entirely (so that the div doesn't need to be closed). If you stop propagation in handlers for elements outside the div, then the document-level handler won't be invoked.
<script>
$(function() { // this will make sure the relevant DOM elements are loaded first
$('.lang-currency-button').click(function(e) {
e.stopPropagation(); // because we don't want to close immediately after opening
$('.lang-currency-field').fadeIn();
});
$('.lang-currency-links').click(function(e) {
e.stopPropagation(); // prevent bubbling since we don't need other handlers.
$('.lang-currency-field').fadeOut();
});
$('.lang-currency-field').click(function(e){
e.stopPropagation(); // prevent bubbling to document handler so div stays open when clicked inside, but not on a link
});
$(document).click(function() {
$('.lang-currency-field').fadeOut();
});
});
</script>
Upvotes: 2
Reputation: 1317
Try
$('page').click(function() { $('.lang-currency-field').fadeOut(); });
Upvotes: 0