Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 772
santa Avatar asked Jan 07 '11 20:01

santa


2 Answers

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();
});
like image 128
Marcus Whybrow Avatar answered Oct 10 '22 04:10

Marcus Whybrow


  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();
       });
    });
    
like image 27
Kees C. Bakker Avatar answered Oct 10 '22 06:10

Kees C. Bakker