Search code examples
jquerystoppropagation

jQuery propagation issue with navigation arrows


Clicking a big image of a trailer (top left) on my page opens a lightbox with a larger version of the image. Then, clicking anywhere closes it with this code:

$(document).on('click', function() {
    $('#fab_gray').remove();
});

However I want to retain the ability to click on navigation left and right arrows (by preventing the lightbox from closing), with this code:

$( '#lightbox_left, #lightbox_right' ).click(function( event ) {
    event.stopPropagation();
});

But it doesn't work: clicking these elements still triggers the code above and closes the lightbox. Why?


Solution

  • Try

    $(document).on('click', function(e) {
        if($(e.target).is("#lightbox_right") || $(e.target).is("#lightbox_left")){ return }
        $('#fab_gray').remove();
    });
    

    Here we're basically checking if the clicked element is any of those arrow buttons. If it is, then we just return. Else it'll go ahead and remove