Search code examples
htmljqueryshow-hidejquery-events

Hide multiple containers using jQuery


I have several dozen objects with an image and a share button on a page at any given time, such as this:

<li class="entry" id="sjDDulC8wt"> 
    <img src="sjDDulC8wt.jpg" />
    <div class="entry_actions">
    <ul class="entry_actions">
        <li class='share_it'><a onclick='javascript: showShare("sjDDulC8wt");' 
        onblur='javascript: hideShare("sjDDulC8wt")' target='_self' 
        title='Share It' class='share_it'>o</a>
        </li>
    </ul>
    <div class="share_options_container"style="display:none;">
        <ul>
            <li><a href="#" class="facebook">F</a></li>
            <li><a href="#" class="twitter">T</a></li>
            <li><a href="#" class="pinterest">X</a></li>
        </ul>
    </div>
</div>

The showShare() function simply opens the share_options_container div inside that particular element of the page when I click on the anchor tag inside the entry_actions ul. When I click off of it, the hideShare() function is supposed to hide it.

function hideShare(id){
$('#' +id+'.share_options_container').hide();
}

When I click on an anchor tag, the corresponding share container div shows up perfectly. When I click off, nothing happens. I've also tried this code, which I found on another similar question:

$("body").click(function(){ $(".share_options_container").fadeOut(200); });

However, when I click on one of the anchors, this function immediately starts fading it back out, so if I changed the fade to hide then the container wouldn't even pop up at all.

Is there an event I can associate my original hideShare() function with such that it will actually trigger when I click off of the anchor tag? If not, can I modify the second function so that it doesn't hide the particular container I'm trying to show as soon as it pops up?


Solution

  • HTML:

    <li class='share_it'><a href="javascript:;" title='Share It' class='share_it'>o</a>
    

    JS:

    $(".share_it a").click(function(){
        $(this).closest(".entry").find(".share_options_container").show();                
        })
    $(".share_options_container").mouseleave(function(){
        $(this).hide();              
        })
    

    ​ ​ demo: http://jsfiddle.net/JP2Vx/2/