Hide an element when the user clicks on 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 the button is pressed .toggle_comments

, the container disappears. Is there a way to do something i.e. fading out if anything outside of the container is clicked when it displays the block? Whereas, it is obvious what .toggle_comments

is outside of it in the first place. So it should be a live event that only fires if the container is in the if state display:block

.

+3


source to share


2 answers


You can bind an event mousedown

to document

and check if an element that is not div[name="comments"]

like this is clicked :



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

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

      

+4


source


Just do different things if you click on other elements

$( 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

+2


source







All Articles