So implementing a few various modals in my web page. My code is as follows.
HTML
<div id="modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h3>Title</h3>
</div>
</div>
JavaScript
<script>
var modal = document.getElementById('modal');
var btn = document.getElementById("mybtn");
var span = document.getElementsByClassName("closeSel")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
all very simple, my issue occurs when i try to add another modal, i change the id value, and add another script for the different modal, which works fine, but when it comes to actually closing the modal it wont work...
For the close button CSS im using the same class, is this what is causing the issue?
/* The close Button */
.close {
color: #aaaaaa;
float: right;
font-style: arial;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
I doubt it would be the classes, I would think more along the IDs as they need to be unique, do you also change the button ID?
If the click and close functionality does not take any parameters, you could just use inline onclick html, then you would be more certain it is not IDs getting messed up.
In the code you are also referencing a class "closeSel" which I do not see in the HTML
You are close, but you need to iterate through each span element. I have attached a working example.
<!-- Test Modal -->
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>First Test text in modal..</p>
</div>
</div>
<!-- Test Modal 2 -->
<div id="myModal2" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Second test text in modal..</p>
</div>
</div>
<script>
var span = document.getElementsByClassName("close");
var modal;
var btn = document.getElementsByClassName("button is-primary is-small modal-button");
for (var i = 0; i < btn.length; i++) {
var thisBtn = btn[i];
thisBtn.addEventListener("click", function(){
modal = document.getElementById(this.dataset.modal);
modal.style.display = "block";
}, false);
}
// iterate through each span element for each modal
for (var i = 0; i < span.length; i++){
span[i].onclick = function(){
modal.style.display = "none";
}
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
Related
I'm trying to code a page where, on clicking different areas of a map, different modals with different content pop up.
However, when I click on either area, the same content shows up (and the "close" button doesn't work).
I gave them different IDs, and they get triggered by different areas. Do you have an idea what the problem can be?
Here's what I have:
.modal { display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0; top: 0; } /* Modal Content/Box */
.modal-content { margin: 15% auto; padding: 20px; } /* The Close Button */
.close { float: right;
font-size: 28px; }
.close:hover, .close:focus { color: black; text-decoration: none; cursor: pointer; }
<map name="2042434">
<area onclick="myFunction1()" shape="poly" coords="46,59,65,45,96,70,198,95,337,173,348,217,348,274,391,296,361,438,235,440,238,258,48,59,61,64" alt="">
<area onclick="myFunction2()" shape="poly" coords="393,296,349,274,347,217,374,208,425,230,440,203,429,162,446,152,513,192,548,184,582,238,577,329,493,380,490,398,409,435,362,440,380,336" alt="">
</map>
<img src="https://www.google.com/imgres?imgurl=https%3A%2F%2Fguide-goyav.com%2Fwp-content%2Fuploads%2F2020%2F05%2FSecteur-de-la-ville.png&imgrefurl=https%3A%2F%2Fguide-goyav.com%2Fvisiter-grenoble%2F&tbnid=3gtWJdaEDshRYM&vet=12ahUKEwjc1tGmvdX4AhUa04UKHWylBqsQMygeegUIARCJAg..i&docid=Zqq3LZ57uAb2-M&w=618&h=626&q=carte%20grenoble&ved=2ahUKEwjc1tGmvdX4AhUa04UKHWylBqsQMygeegUIARCJAg" alt="" border="0" width="703" height="794" usemap="#2042434">
<!-- MODAL 1 -->
<div id="modal1" class="modal">
<div class="modal-content">
<span class="close">×</span> <!--the close button-->
<p>Some text in the Modal..</p>
</div>
</div>
<script>var modal=document.getElementById("modal1");
var span=document.getElementsByClassName("close")[0];
function myFunction1() {
modal.style.display="block";
}
span.onclick=function() {
modal.style.display="none";
}
window.onclick=function(event) {
if (event.target==modal1) {
modal.style.display="none";
}
}
</script>
<!-- MODAL 2 -->
<div id="modal2" class="modal">
<div class="modal-content">
<span class="close">×
</span><p>So2ext 2 th2Mo22..</p>
</div>
</div>
<script>var modal=document.getElementById("modal2");
var span=document.getElementsByClassName("close")[0];
function myFunction2() {
modal.style.display="block";
}
span.onclick=function() {
modal.style.display="none";
}
window.onclick=function(event) {
if (event.target==modal2) {
modal.style.display="none";
}
}
</script>
---------solution/final code----------
<map name="2042434">
<area id="area1" shape="poly" coords="46,59,65,45" alt="">
<area id="area2" shape="poly" coords="393,296,349,274" alt="">
</map>
<img src="https://www.google.com/imgres?imgurl=https%3A%2F%2Fguide-goyav.com%2Fwp-content%2Fuploads%2F2020%2F05%2FSecteur-de-la-ville.png&imgrefurl=https%3A%2F%2Fguide-goyav.com%2Fvisiter-grenoble%2F&tbnid=3gtWJdaEDshRYM&vet=12ahUKEwjc1tGmvdX4AhUa04UKHWylBqsQMygeegUIARCJAg..i&docid=Zqq3LZ57uAb2-M&w=618&h=626&q=carte%20grenoble&ved=2ahUKEwjc1tGmvdX4AhUa04UKHWylBqsQMygeegUIARCJAg" alt="" border="0" width="703" height="794" usemap="#2042434">
<!-- MODAL SEC1 -->
<div id="modal1" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
<!-- MODAL SEC2-->
<div id="modal2" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>So2ext 2 th2Mo22..</p>
</div>
</div>
<script>
function closeModal() {
document.querySelectorAll('.modal').forEach(function (modal) {
modal.style.display = 'none';
})
}
document.querySelectorAll('span.close').forEach(function (element) {
//close all modal
element.addEventListener('click', function (e) {
closeModal();
})
});
(function myFunction1() {
// your code here will be safe and won't pollute other areas of your code
var modal = document.getElementById("modal1");
var span = document.getElementsByClassName("close")[0];
var area = document.getElementById("area1");
area.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.addEventListener('click', function(event) {
if (event.target==modal1){
closeModal();
}
});
})();
(function myFunction2() {
var modal = document.getElementById("modal2");
var span = document.getElementsByClassName("close")[0];
var area = document.getElementById("area2");
area.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.addEventListener('click', function(event) {
if (event.target==modal2){
closeModal();
}
});
})();
</script>
<button id="btn1">button 1</button>
<button id="btn1">button 2</button>
<script>
(function() {
// your code here will be safe and won't pollute other areas of your code
// however, window.something is global and shared by your code
})();
</script>
<div id="modal1" class="modal">
<div class="modal-content">
<span class="close">×</span> <!--the close button-->
<p>Some text in the Modal..</p>
</div>
</div>
<!-- MODAL 2 -->
<div id="modal2" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>So2ext 2 th2Mo22..</p>
</div>
</div>
function closeModal() {
document.querySelectorAll('.modal').forEach(function (modal) {
modal.style.display = 'none';
})
}
document.querySelectorAll('span.close').forEach(function (element) {
//close all modal
element.addEventListener('click', function (e) {
closeModal();
}
)
});
document.querySelectorAll('.modal').forEach(function (element) {
//close all modal
element.addEventListener('click', function (e) {
e.stopPropagation();
e.preventDefault();
}
)
});
function myFunction1() {
let modal = document.getElementById("modal1");
modal.style.display = "block";
}
function myFunction2() {
let modal = document.getElementById("modal2");
modal.style.display = "block";
}
const getParents = el => {
for (var parents = []; el; el = el.parentNode) {
parents.push(el.id);
}
return parents.join(',');
};
document.body.addEventListener('click', (e) => {
let element = getParents(e.target);//return: ,,modal2,,, or ,,modal1,,,
if(element.includes("modal")===-1){
//click outside modal
closeModal();
}
}, true);
a beginner here, i'm trying to make a modal that will be shown once the share button is clicked and i don't seem to find why the onclick function isn't executed, the idea is once the share button is clicked the display:none; will be changed to display:block, so either there is a problem with style.display="block" or, which is more probable, i suck .
Any help is appreciated.
Thank you previously.
HTML code:
<div class="navbar-container">
<div class="nav nav-1" >
<button class="btn btn-1" id="sharebtn">Share </button>
</div>
<div class="nav nav-2">
<button class="btn btn-2" id="howbtn">how does it work ?</button>
</div>
<div class="nav nav-3" >
<button class="btn btn-3" id="abouttns">About</button>
</div>
</div>
<!---Creating the modals-->
<div id="modal-share">
<div class="modal-header">
<button class="close-share">×</button>
</div>
<div class="link">
<input type="text" class="link-input" placeholder="www.youtube.com/jdlkfsjakfdsa">
<button id="share-btn" onclick="fuck">share</button>
</div>
<div class="description">
<input type="text" max="50" placeholder="cats are not that smart">
</div>
</div>
CSS code:
#modal-share{
display: none; /*hidden by default*/
position: fixed; /*staying in the center even when scrolling*/
z-index: 1; /*stays on top of grids, 3D translation*/
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: white; /*color of the modal*/
background-color: rgba(0,0,0,0.4); /*color of the background*/
border:1px solid black;
}
Javascript code:
<script>
var modal=document.getElementById("modal-share");
var share_btn=document.getElementsById("sharebtn");
var close_share=document.getElementsByClassName("close-share");
share_btn.onclick=function(){
modal.style.display="block";
}
close_share.onclick=function(){
modal.style.display="none";
}
window.onclick=function(event){
if(event.target==modal){
modal.style.display="none";
}
}
</script>
There is actually an error in your script which is causing everything else to fail, namely
var share_btn=document.getElementsById("sharebtn");
There is no function document.getElementsById, only document.getElementById. I have your code working with the fix on the following link -
https://jsfiddle.net/2pfzc4gL/
There is a typo in your script which is causing the issue.
var share_btn=document.getElementsById("sharebtn");
it should be getElementById instead of getElementsById.
it would be better if we use querySelector for querying DOM element and for events addEventListener instead of overriding the click function
var share_btn = document.querySelector("#sharebtn");
var close_share = document.querySelector(".close-share");
var modal = document.querySelector("#modal-share");
share_btn.addEventListener("click", function () {
modal.style.display = "block";
});
close_share.addEventListener("click", function () {
modal.style.display = "none";
});
window.addEventListener("click", function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
});
Two things, first there's a typo in your code getElementsById should be getElementById. And the second is that getElementsByClassName returns an array like collection of elements so you need to retrieve the first one from the array. Here's the updated javascript.
const modal = document.getElementById("modal-share");
const share_btn = document.getElementById("sharebtn"); // typo here in original
const close_share = document.getElementsByClassName("close-share")[0]; // select first element in HTML collection
share_btn.onclick = function () {
modal.style.display = "block";
}
close_share.onclick = function () {
modal.style.display = "none";
}
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
I've created a CSS grid that has five buttons. Each to open a different modal window. These windows should be able to close by pressing the top right X or anywhere outside the window.
Why the JavaScript only work in the final window (#poravasara)?
My JavaScript code has lots of repetition. Is there a way to pack it, or write it more efficient?
HTML
<div class="container">
<div class="g1">
<div class="työkalu">
<div id="vasara" class="animation-div shake-slow shake-constant shake-constant-hover">
<img src="http://placekitten.com/g/200/301" alt="">
<!-- Trigger/Open The Modal -->
<button id="avaaVasara" class="valitsija">+</button>
<h3>Red</h3>
</div>
<!-- The Modal -->
<div id="vasaraIkkuna" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="suljeVasara" class="close">×</span>
<h3>Red</h3>
<p>What the heck just happened, something feels fishy cat meoooow i iz master of hoomaan, not hoomaan master of i, oooh damn dat dog so be superior poop in the plant pot, get video posted to internet for chasing red dot. Kitty scratches couch bad kitty scratch the postman wake up lick paw wake up owner meow meow i will ruin the couch with my claws. Shake treat bag chase after silly colored fish toys around the house but take a big fluffing crap 💩. Fall over dead (not really but gets sypathy) i'm going to lap some water out of my master's cup meow or eat grass, throw it back up. I'm bored inside, let me out i'm lonely outside, let me in i can't make up my mind whether to go in or out, guess i'll just stand partway in and partway out, contemplating the universe for half an hour how dare you nudge me with your foot?!?! leap into the air in greatest offense!</p>
</div>
</div>
</div>
</div>
<div class="g2">
<div class="työkalu">
<div id="ruuviväännin" class="animation-div shake-slow2 shake-constant2 shake-constant-hover2">
<img src="http://placekitten.com/g/198/302" alt="">
<!-- Trigger/Open The Modal -->
<button id="avaaRuuviväännin" class="valitsija">+</button>
<h3>Blue</h3>
</div>
<!-- The Modal -->
<div id="ruuviväänninIkkuna" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="suljeRuuviväännin" class="close">×</span>
<h3>Blue</h3>
<p>Purrrrrr hit you unexpectedly missing until dinner time eat a rug and furry furry hairs everywhere oh no human coming lie on counter don't get off counter and murr i hate humans they are so annoying run outside as soon as door open. Cat gets stuck in tree firefighters try to get cat down firefighters get stuck in tree cat eats firefighters' slippers kitty scratches couch bad kitty yet plan steps for world domination and annoy kitten brother with poking i heard this rumor where the humans are our owners, pfft, what do they know?!</p>
</div>
</div>
</div>
</div>
<div class="g3">
<div class="työkalu">
<div id="kulmahiomakone" class="animation-div shake-slow3 shake-constant3 shake-constant-hover3">
<img src="http://placekitten.com/g/200/303" alt="">
<!-- Trigger/Open The Modal -->
<button id="avaaKulmahiomakone" class="valitsija">+</button>
<h3>Orange</h3>
</div>
<!-- The Modal -->
<div id="kulmahiomakoneIkkuna" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="suljeKulmahiomakone" class="close">×</span>
<h3>Orange</h3>
<p>Show belly throw down all the stuff in the kitchen swat at dog cough hairball on conveniently placed pants. Meow meow we are 3 small kittens sleeping most of our time, we are around 15 weeks old i think.</p>
</div>
</div>
</div>
</div>
<div class="g4">
<div class="työkalu">
<div id="pistosaha" class="animation-div shake-slow4 shake-constant4 shake-constant-hover4">
<img src="http://placekitten.com/g/200/304" alt="">
<!-- Trigger/Open The Modal -->
<button id="avaaPistosaha" class="valitsija">+</button>
<h3>White</h3>
</div>
<!-- The Modal -->
<div id="pistosahaIkkuna" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="suljePistosaha" class="close">×</span>
<h3>White</h3>
<p>Spread kitty litter all over house ooooh feather moving feather! funny little cat chirrup noise shaking upright tail when standing next to you get video posted to internet for chasing red dot. Experiences short bursts of poo-phoria after going to the loo man running from cops stops to pet cats, goes to jail damn that dog your pillow is now my pet bed yet attempt to leap between furniture but woefully miscalibrate and bellyflop onto the floor; what's your problem?</p>
</div>
</div>
</div>
</div>
<div class="g5">
<div class="tekijä-div">
<img id="tekijä" src="http://placekitten.com/200/300" alt="">
</div>
</div>
<div class="g6">
<div class="työkalu">
<div id="poravasara" class="animation-div shake-slow6 shake-constant6 shake-constant-hover6">
<img src="http://placekitten.com/g/199/306" alt="">
<!-- Trigger/Open The Modal -->
<button id="avaaPoravasara" class="valitsija">+</button>
<h3>Stripes</h3>
</div>
<!-- The Modal -->
<div id="poravasaraIkkuna" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="suljePoravasara" class="close">×</span>
<h3>Stripes</h3>
<p>Pose purrfectly to show my beauty poop on floor and watch human clean up sit on human. Cats are a queer kind of folk 𝕄𝔼𝕆𝕎 fart in owners food but sugar, my siamese, stalks me (in a good way), day and night this cat happen now, it was too purr-fect!!! so jump launch to pounce upon little yarn mouse, bare fangs at toy run hide in litter box until treats are fed so find a way to fit in tiny box.</p>
</div>
</div>
</div>
</div>
</div>
CSS
.container {
display: grid;
/* grid-template-columns: auto auto auto;
grid-template-rows: auto auto auto; */
grid-template-columns: 33.3% 33.3% 33.3%;
grid-template-rows: 33.3% 33.3% 33.3%;
max-width: 1200px;
margin: 0 auto;
justify-items: center;
align-items: center;
}
/* MODAL */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
position: relative;
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
max-width: 400px; /* Could be more or less, depending on screen size */
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: animatetop;
animation-duration: 0.4s
}
/* Add Animation */
#-webkit-keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
/* MODAL END */
JAVASCRIPT
// Näytä työkalu pop-up -ikkunat
// MODAL vasara
var vasaraModal = document.getElementById("vasaraIkkuna");
// Get the button that opens the modal
var vasaraBtn = document.getElementById("avaaVasara");
// Get the <span> element that closes the modal
var vasaraSpan = document.getElementById("suljeVasara");
// When the user clicks on the button, open the modal
vasaraBtn.onclick = function() {
vasaraModal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
vasaraSpan.onclick = function() {
vasaraModal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == vasaraModal) {
vasaraModal.style.display = "none";
}
}
//
// MODAL ruuviväännin
var ruuviväänninModal = document.getElementById("ruuviväänninIkkuna");
// Get the button that opens the modal
var ruuviväänninBtn = document.getElementById("avaaRuuviväännin");
// Get the <span> element that closes the modal
var ruuviväänninSpan = document.getElementById("suljeRuuviväännin");
// When the user clicks on the button, open the modal
ruuviväänninBtn.onclick = function() {
ruuviväänninModal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
ruuviväänninSpan.onclick = function() {
ruuviväänninModal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == ruuviväänninModal) {
ruuviväänninModal.style.display = "none";
}
}
//
// MODAL kulmahiomakone
var kulmahiomakoneModal = document.getElementById("kulmahiomakoneIkkuna");
// Get the button that opens the modal
var kulmahiomakoneBtn = document.getElementById("avaaKulmahiomakone");
// Get the <span> element that closes the modal
var kulmahiomakoneSpan = document.getElementById("suljeKulmahiomakone");
// When the user clicks on the button, open the modal
kulmahiomakoneBtn.onclick = function() {
kulmahiomakoneModal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
kulmahiomakoneSpan.onclick = function() {
kulmahiomakoneModal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == kulmahiomakoneModal) {
kulmahiomakoneModal.style.display = "none";
}
}
//
// MODAL pistosaha
var pistosahaModal = document.getElementById("pistosahaIkkuna");
// Get the button that opens the modal
var pistosahaBtn = document.getElementById("avaaPistosaha");
// Get the <span> element that closes the modal
var pistosahaSpan = document.getElementById("suljePistosaha");
// When the user clicks on the button, open the modal
pistosahaBtn.onclick = function() {
pistosahaModal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
pistosahaSpan.onclick = function() {
pistosahaModal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == pistosahaModal) {
pistosahaModal.style.display = "none";
}
}
//
// MODAL poravasara
var poravasaraModal = document.getElementById("poravasaraIkkuna");
// Get the button that opens the modal
var poravasaraBtn = document.getElementById("avaaPoravasara");
// Get the <span> element that closes the modal
var poravasaraSpan = document.getElementById("suljePoravasara");
// When the user clicks on the button, open the modal
poravasaraBtn.onclick = function() {
poravasaraModal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
poravasaraSpan.onclick = function() {
poravasaraModal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == poravasaraModal) {
poravasaraModal.style.display = "none";
}
}
//
You can find the DEMO in CodePen https://codepen.io/konspaul/pen/MWwddvW
This seems to be working :
I removed all event listeners and replaced it by a unique ev
See : window.onclick = function(event) only works for first item
// Näytä työkalu pop-up -ikkunat
// MODAL vasara
var vasaraModal = document.getElementById("vasaraIkkuna");
// Get the button that opens the modal
var vasaraBtn = document.getElementById("avaaVasara");
// Get the <span> element that closes the modal
var vasaraSpan = document.getElementById("suljeVasara");
// When the user clicks on the button, open the modal
vasaraBtn.onclick = function() {
vasaraModal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
vasaraSpan.onclick = function() {
vasaraModal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
document.body.onclick = function(event) {
if (event.target.className.includes("modal")) {
event.target.style.display = "none";
}
}
//
// MODAL ruuviväännin
var ruuviväänninModal = document.getElementById("ruuviväänninIkkuna");
// Get the button that opens the modal
var ruuviväänninBtn = document.getElementById("avaaRuuviväännin");
// Get the <span> element that closes the modal
var ruuviväänninSpan = document.getElementById("suljeRuuviväännin");
// When the user clicks on the button, open the modal
ruuviväänninBtn.onclick = function() {
ruuviväänninModal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
ruuviväänninSpan.onclick = function() {
ruuviväänninModal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
// MODAL kulmahiomakone
var kulmahiomakoneModal = document.getElementById("kulmahiomakoneIkkuna");
// Get the button that opens the modal
var kulmahiomakoneBtn = document.getElementById("avaaKulmahiomakone");
// Get the <span> element that closes the modal
var kulmahiomakoneSpan = document.getElementById("suljeKulmahiomakone");
// When the user clicks on the button, open the modal
kulmahiomakoneBtn.onclick = function() {
kulmahiomakoneModal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
kulmahiomakoneSpan.onclick = function() {
kulmahiomakoneModal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
//
// MODAL pistosaha
var pistosahaModal = document.getElementById("pistosahaIkkuna");
// Get the button that opens the modal
var pistosahaBtn = document.getElementById("avaaPistosaha");
// Get the <span> element that closes the modal
var pistosahaSpan = document.getElementById("suljePistosaha");
// When the user clicks on the button, open the modal
pistosahaBtn.onclick = function() {
pistosahaModal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
pistosahaSpan.onclick = function() {
pistosahaModal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
//
// MODAL poravasara
var poravasaraModal = document.getElementById("poravasaraIkkuna");
// Get the button that opens the modal
var poravasaraBtn = document.getElementById("avaaPoravasara");
// Get the <span> element that closes the modal
var poravasaraSpan = document.getElementById("suljePoravasara");
// When the user clicks on the button, open the modal
poravasaraBtn.onclick = function() {
poravasaraModal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
poravasaraSpan.onclick = function() {
poravasaraModal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
//
I have a webpage with several buttons. Those buttons trigger a modal with content in it. Each button is associated with a unique modal with unique content in it.
The problem is every button triggers the modal associated with the last button at the bottom of the page.
Each button and modal have a unique id, so I don't understand why this is happening.
Here's the code I used to create each of those buttons.
Thank you for your help!
// JS CODE FOR THE FIRST MODAL
// Get the modal
var modal = document.getElementById('modal-1');
// Get the button that opens the modal
var btn = document.getElementById("button-1");
// Get the <span> element that closes the modal
var span = document.getElementById("close-1");
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
// When the user press ESC key, close the modal
window.onkeydown = function( event ) {
if ( event.keyCode == 27 ) {
modal.style.display = "none";
}
};
// JS CODE FOR THE SECOND MODAL
// Get the modal
var modal = document.getElementById('modal-2');
// Get the button that opens the modal
var btn = document.getElementById("button-2");
// Get the <span> element that closes the modal
var span = document.getElementById("close-2");
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
// When the user press ESC key, close the modal
window.onkeydown = function( event ) {
if ( event.keyCode == 27 ) {
modal.style.display = "none";
}
};
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1001; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgb(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
margin: auto;
padding: auto;
width: 60%;
}
/* The Close Button */
.close {
color: white;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<!-- Trigger/Open The Modal #1 -->
<a id="button-1">Modal #1</a>
<!-- The Modal -->
<div id="modal-1" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="close-1" class="close">×</span>
<p>I'm the text of the first modal</p>
</div>
</div>
<!-- Trigger/Open The Modal #2 -->
<a id="button-2">Modal #2</a>
<!-- The Modal -->
<div id="modal-2" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="close-2" class="close">×</span>
<p>I'm the text of the second modal</p>
</div>
</div>
isn't it because you miss to add some event stopPropagation ?
(and I think it is a bad idea to name a JS vaviable "span", this a name of html tag)
and it shoud be more clear to code on this way (same event for serveral elements)
var ActionCloseID = ['modal', 'button', 'close'];
document.onclick = function(e) {
if (ActionCloseID.includes(e.target.id) ) {
e.stopPropagation();
modal.style.display = "none";
}
}
<script>
// JS CODE FOR THE FIRST MODAL
// Get the modal
var modal = document.getElementById('modal-1');
// Get the button that opens the modal
var btn = document.getElementById("button-1");
// Get the <span> element that closes the modal
var span = document.getElementById("close-1");
// Get the modal
var modal2 = document.getElementById('modal-2');
// Get the button that opens the modal
var btn2 = document.getElementById("button-2");
// Get the <span> element that closes the modal
var span2 = document.getElementById("close-2");
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}else if (event.target == modal2) {
modal2.style.display = "none";
}
}
// When the user press ESC key, close the modal
window.onkeydown = function( event ) {
if ( event.keyCode == 27 ) {
modal.style.display = "none";
modal2.style.display = "none";
}
};
// When the user clicks the button, open the modal
btn2.onclick = function() {
modal2.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span2.onclick = function() {
modal2.style.display = "none";
}
Please update your script like this, this should work.
Very new to coding here, but I am coding a web app, and I want to have two buttons at the top of the page. one to login/create an account, and another to add a review of the page. I added the first button and got it to display a modal when it was pressed, this all worked fine. I then tried to add a second button that would display another modal, but now both buttons only display the second modal.
Each modal had a small 'x' at the top right corner to exit and this also doesn't work now. Here is my code
The style is all in the head.
/* The Modal (background) */
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.3); /* Used to grey out the rest of the screen */
}
/* Modal Content */
.modal-content {
background-color: #fefefe; /* Background colour of Modal */
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 50%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
The rest of the code is all in the body.
<h2>Modal Testing</h2>
<!-- Buttons to open Modals -->
<button id="loginBtn">Account</button>
<button id="reviewBtn">Add Review</button>
<!-- The Modals -->
<!-- Login/Create Account Modal -->
<div id="loginModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Login details</p>
<!-- Allows the user to input information-->
<form action="/action_page.php">
Username:<br>
<input type="text" name="username" value="">
<br>
Password:<br>
<input type="password" value="" id="userInput">
<br><br>
<input type="checkbox" onclick="visible()">Show Password
</form>
<button id="signInBtn">Sign In</button>
<p>Not got an account? Sign up now!</p>
<button id="signUpBtn">Sign Up</button>
<button id="cancelBtn">Cancel</button>
</div>
</div>
<script>
function visible(){
var x = document.getElementById("userInput");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
</script>
<script>
// Get the modal
var modal = document.getElementById('loginModal');
// Get the button that opens the modal
var btn = document.getElementById("loginBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
<!-- Add Review Modal -->
<div id="addReviewModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Add Review</p>
<!-- Allows the user to input information-->
<form action="/review_page.php">
Location:<br>
<input type="text" name="location" value="">
<br>
Comments:<br>
<input type="text" name="comments" value="">
<br>
</form>
<button id="submitBtn">Submit Review</button>
<button id="cancelBtn">Cancel</button>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('addReviewModal');
// Get the button that opens the modal
var btn = document.getElementById("reviewBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
You are using your JavaScript in different <script> tags. This does not mean that they are seperate blocks, They just get appended to each other. This means, that when you declare the Variable modal in one block and then declare it again in the second block, the Variable will get overwrited. I changed the Var names to XXX1 and XXX2.
function visible(){
var x = document.getElementById("userInput");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
// Get the modal
var modal1 = document.getElementById('loginModal');
// Get the button that opens the modal
var btn1 = document.getElementById("loginBtn");
// Get the <span> element that closes the modal
var span1 = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn1.onclick = function() {
modal1.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span1.onclick = function() {
modal1.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal1) {
modal1.style.display = "none";
}
}
// Get the modal
var modal2 = document.getElementById('addReviewModal');
// Get the button that opens the modal
var btn2 = document.getElementById("reviewBtn");
// Get the <span> element that closes the modal
var span2 = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn2.onclick = function() {
modal2.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span2.onclick = function() {
modal2.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal2) {
modal2.style.display = "none";
}
}
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.3); /* Used to grey out the rest of the screen */
}
/* Modal Content */
.modal-content {
background-color: #fefefe; /* Background colour of Modal */
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 50%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<h2>Modal Testing</h2>
<!-- Buttons to open Modals -->
<button id="loginBtn">Account</button>
<button id="reviewBtn">Add Review</button>
<!-- The Modals -->
<!-- Login/Create Account Modal -->
<div id="loginModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Login details</p>
<!-- Allows the user to input information-->
<form action="/action_page.php">
Username:<br>
<input type="text" name="username" value="">
<br>
Password:<br>
<input type="password" value="" id="userInput">
<br><br>
<input type="checkbox" onclick="visible()">Show Password
</form>
<button id="signInBtn">Sign In</button>
<p>Not got an account? Sign up now!</p>
<button id="signUpBtn">Sign Up</button>
<button id="cancelBtn">Cancel</button>
</div>
</div>
<!-- Add Review Modal -->
<div id="addReviewModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Add Review</p>
<!-- Allows the user to input information-->
<form action="/review_page.php">
Location:<br>
<input type="text" name="location" value="">
<br>
Comments:<br>
<input type="text" name="comments" value="">
<br>
</form>
<button id="submitBtn">Submit Review</button>
<button id="cancelBtn">Cancel</button>
</div>
</div>
Now the buttons open the corresponding modal.
I will post an update if I figured yout the "Close on X" thing.
Sorry for my bad english ;)
instead of
document.getElementsByClassName("close")[0];
use
modal.getElementsByClassName("close")[0];