andy
andy

Reputation: 2754

Hide an element when a user clicks outside of it

$( document ).on('click', '.toggle_comments', function( event ){

    event.preventDefault();

    var container = $('div[name="comments"]');

    if ( container.css('display') == 'block' ) {

        container.hide();

        return;
    }

    container.fadeIn(500);
});

When .toggle_comments is clicked, the container fades in. Is there a way to do something, ie fadeout, if anything outside the container is clicked WHILE it's display block? Bearing in mind, obviously, that .toggle_comments is outside of it in the first place. So it needs to be a live event, something that only fires while the container is in the state if display:block.

Upvotes: 3

Views: 62

Answers (2)

Jordan Doyle
Jordan Doyle

Reputation: 3026

You can bind a mousedown event to document and check if the element clicked on is not div[name="comments"] like so:

$(document).mousedown(function(event)
{
    var commentSection = $('div[name="comments"]');

    if(!$(commentSection).is($(event.target)) && !$(event.target).closest($(commentSection)).length)
        $(commentSection).fadeOut();
});

Upvotes: 4

adeneo
adeneo

Reputation: 318352

Just do different things if different elements are clicked

$( document ).on('click', function( event ){
    event.preventDefault();

    var target    = $(event.target);
    var container = $('div[name="comments"]');

    if ( target.closest('.toggle_comments').length > 0 ) {
        if ( container.is(':visible') ) {
            container.hide();
        } else {
            container.fadeIn(500);
        }
    } else if (target.closest(container).length === 0 && container.is(':visible')) {
        container.fadeOut(500); 
    } 
});

FIDDLE

Upvotes: 2

Related Questions