简体   繁体   中英

how to close modal pop up forms by clicking anywhere on the screen

I have created two modal pop up forms...one of the form is to log in and the other is to register.

only one form can be open at any one time, and i am trying to make them close if the user clicks anywhere outside of the form. i can make one of them close, but not the other.

I have shown my code which it is linked to. please follow the link below. the link does have some errors but you should get the idea. one of the form id is 'id01' and the others is 'id02' does anyone have any ideas?

once on the link please select If you have an account please click here OR If you have not had an account please click here for the forms to come up

https://jsfiddle.net/z6atq0ww/

the code which it is linked to is

var modal = document.getElementById('id02');

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        document.getElementById('id02').style.display = "none";   

    }
}
</script>

Thanks

You should make a transparent modal background that covers the entire page. On top of that place your displayed form. Then you can simply add a click handler to the modal background.

try using jquery

$('.click-btn').click(function(){
       $('.modal').show(); //show popup
    })

    $('body').click(function(){
       $('.modal').hide(); //hide modal
    })

    $('.click-btn, .modal').click(function(e){
       e.stopPropagation; // don't close modal by clicking inside modal and by clicking btn
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM