简体   繁体   中英

Hide div on blur

I have a jQuery function where when an element is clicked a hidden div shows.

$('.openHide').click(function(){
    $(this).next('.hiddenContent').toggle();
});

I need to modify it s that I could close this div if I click back not just on the first element. Possibly on Blur, but I am not sure how to indicate the element...

$('.hiddenContent').blur(function() {
    $('.hiddenContent').parent().children('.hiddenContent').hide();
});

Here's my HTML:

<span class="openHide">text here</span>
<div style="display:none" class="hiddenContent">
     hidden content here
</div>
  1. On the click on the span the div should be toggled
  2. On the body click the div should be hidden
  3. On the click on the div, the event should not be propagated to the body
  4. On the click on the span the event should not be propagated to the body

     $(document).ready(function() { $('.openHide').click(function(e) { $('.hiddenContent').toggle(); e.stopPropagation(); }); $(document.body).click(function() { $('.hiddenContent').hide(); }); $('.hiddenContent').click(function(e) { e.stopPropagation(); }); }); 

If .hiddenContent is a div you won't be able to use blur, that only works on text inputs. mouseout may be an alternative, and $(this) is what I think you are looking for in this case:

$('.hiddenContent').mouseout(function() {
    $(this).hide();
});

Hide on clicking elsewhere

If you want to hide the div when you click outside the element you must watch for clicks all over the body of the page:

$('body').click(function() {
    // Hide all hidden content
    $('.hiddenContent').hide();
});

And then provide and exception for when you are clicking on the actually hidden content itself, and when you want to open it:

$('.hiddenContent').click(function(e) { e.stopPropagation() });

$('.openHide').click(function(e) {
    $(this).next('.hiddenContent').toggle();
    // this stops the event from then being caught by the body click binding
    e.stopPropagation();
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM