Reputation: 3
I have question because i have a problem with JS code on my website. I created 7 popups in Js file and i attached that file to my index.php. When I use all of them only the last is working
index.php (fragment)
<div id="popupBox_1">
<div class="popupBoxWrapper">
<div class="popupBoxContent">
<h3>Popup 1</h3>
<p>Obecnie przeglądasz okienko 1</p>
</div>
</div>
</div>
<div id="popupBox_2">
<div class="popupBoxWrapper">
<div class="popupBoxContent">
<h3>Popup 2</h3>
<p>Obecnie przeglądasz okienko 2</p>
</div>
</div>
</div>
<div id="popupBox_3">
<div class="popupBoxWrapper">
<div class="popupBoxContent">
<h3>Popup 3</h3>
<p>Obecnie przeglądasz okienko 3</p>
</div>
</div>
</div>
popup.js (fragment)
window.onclick = function(event) {
if (event.target == popupBox_1) {
popupBox_1.style.display = "none";
}
}
window.onclick = function(event) {
if (event.target == popupBox_2) {
popupBox_2.style.display = "none";
}
}
window.onclick = function(event) {
if (event.target == popupBox_3) {
popupBox_3.style.display = "none";
}
}
I made these popups and they are working correctly but I created that functions in js because I want to close them when user click outside popup. And it's only working for the last i have defined (I mean popupBox_3) and i want to make them all working!!!
PLEASE I NEED YOUR HELP!
Upvotes: 0
Views: 38
Reputation: 36511
You can't assign multiple click event handlers using Node.onclick
, each time you do that you overwrite the last one. You could switch to
window.addEventListener('click', function() {
if (event.target == popupBox_1) {
popupBox_1.style.display = "none";
}
});
window.addEventListener('click', function() {
if (event.target == popupBox_2) {
popupBox_2.style.display = "none";
}
});
...etc.
But it would make a lot more sense to just move all three conditions into one click handler:
window.onclick = function(event) {
if (event.target == popupBox_1) {
popupBox_1.style.display = "none";
}
if (event.target == popupBox_2) {
popupBox_2.style.display = "none";
}
if (event.target == popupBox_3) {
popupBox_3.style.display = "none";
}
}
Upvotes: 2