stact overflowsam1
stact overflowsam1

Reputation: 77

Window.onclick not working in modal box

I have a modal box of html inside a php foreach loop. I am using javascript to display and hide the modal box by using onclick event. The Problem is bot my onclick event to display and hide functions are working, but when I click on the window outside the modal box it's not hiding the modal box.

I think It might be because I an printing several modal box in the php loop and the javascript does not know which one to close.

I just want to close all the modal box but don't know how to get it done

Thanks in advance

My javascript:

<script>
// Get the modal
var currentIndex;
var modal = document.getElementsByClassName('myModal');

// Get the button that opens the modal
var btn = document.getElementsByClassName("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close");

// When the user clicks the button, open the modal 
    function display(index) {
            modal[index].style.display = "block";
        currentIndex = index;
    } 

function notdisplay(index){
        modal[index].style.display = "none";

    }

// When the user clicks on <span> (x), close the modal

// When the user clicks anywhere outside of the modal, close it


window.onclick = function(event) {
    if (event.target == modal[currentIndex]) {
        modal.style.display = "none";
    }
}

</script>

My modal box inside the php loop:

<div class="col-md-7 offset-md-2 myBtn" onclick="display('.$index.')" style="margin-left:20px;">
<span onclick="notdisplay('.$index.')" class="close">&times;</span>

Upvotes: 0

Views: 3924

Answers (1)

Minh Dang
Minh Dang

Reputation: 81

You can give access to the index by declare a global variable (let's say var currentIndex) of the script. Then inside display(index) method change the global variable to index.

var currentIndex;
function display(index) {
        modal[index].style.display = "block";
        currentIndex = index;

} 

then inside window.onclick function you can access the currentIndex

window.onclick = function(event) {

    if (event.target == modal[currentIndex]) {
        modal.style.display = "none";
    }
}

Upvotes: 2

Related Questions