Search code examples
twitter-bootstrapbootstrap-modallightbox

How do I close a Bootstrap/Lightbox modal by clicking anywhere within the viewport?


When the Lightbox image appears, I can only close the modal by clicking outside of it. I would like to close the modal by clicking anywhere within the viewport, as well as with Esc or Space Bar.


Solution

  • I hope I'm understanding your question properly. The way I read is that you also want to close the modal/ lightbox when clicking inside it. This would be accomplished like this:

    $('#yourModalID').on('click', function(){
        $(this).modal('close');
    });
    

    You also want to close the modal on a spacebar press. You could do this like that:

    $('body').on('keyup', function(event){
        if (event.keyCode == 32){ //check if the key pressed was the space bar
             $('#yourModalID').modal('hide');
        }
    });
    

    You should probably only add this event listener when opening the modal and remove it when the modal is closed to get better performance.