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];
Related
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 need to propagate different content within a modal on a click of a button. My problem is—calling out the div element within JavaScript. As of right now, it's an ID and I can't have multiple ID's. I am very confused by everything since I am new to JS.
The simplest form, I just need button 1 to link with button 1, button 2 with button 2, and so on. I'm not sure what to change in my JS for this to work.
http://jsfiddle.net/mbLj68ua/10/
<button id="modalbutton" class="modalbutton">Open Modal 1</button>
<button id="modalbutton" class="modalbutton">Open Modal 2</button>
<button id="modalbutton" class="modalbutton">Open Modal 3</button>
<!-- Content 1 -->
<div id="detailmodal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>1 Modal Header</h2>
</div>
<div class="modal-body">
<p>please link with 1</p>
<p>Some other text...</p>
</div>
<div class="modal-footer"><h3>Modal Footer</h3></div>
</div>
</div>
<!-- Content 2 -->
<div id="detailmodal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>2 Modal Header</h2>
</div>
<div class="modal-body">
<p>please link with 2</p>
<p>Some other text...</p>
</div>
<div class="modal-footer"><h3>Modal Footer</h3></div>
</div>
</div>
<!-- Content 3 -->
<div id="detailmodal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>3 Modal Header</h2>
</div>
<div class="modal-body">
<p>please link with 3</p>
<p>Some other text...</p>
</div>
<div class="modal-footer"><h3>Modal Footer</h3></div>
</div>
</div>
Script:
// Get the <span> element that closes the modal
var span = document.getElementsByClassName('close')[0];
// When the user clicks the buttons open the modal
for (let i = 0; i < btn.length; i++) {
btn[i].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';
}
};
You need to differentiate between them using the index document.getElementsByClassName('modal')[i]
Try it now:
// Get the modal
var modal = document.getElementById('detailmodal');
// Get the button that opens the modal
var btn = document.getElementsByClassName("modalbutton");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close");
// When the user clicks the buttons open the modal
for (let i = 0; i < btn.length; i++) {
btn[i].onclick = function() {
document.getElementsByClassName('modal')[i].style.display = "block";
}
}
for (let i = 0; i < span.length; i++) {
// When the user clicks on <span> (x), close the modal
span[i].onclick = function() {
document.getElementsByClassName('modal')[i].style.display = "none";
}
}
// When the user clicks anywhere outside of the modal, close it
for (let i = 0; i < window.length; i++) {
window[i].onclick = function(event) {
if (event.target == modal) {
document.getElementsByClassName('modal')[i].style.display = "none";
}
}}
/* The Modal (background) */
.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 */
.modal-content {
position: relative;
float: right;
background-color: #fefefe;
margin: auto;
padding: 0;
border: 1px solid #888;
max-width: 850px;
width: 100%;
height: 100%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: animatetop;
animation-duration: 0.8s
}
/* Add Animation */
#-webkit-keyframes animatetop {
from {right:-100px; opacity:0}
to {right:0; opacity:1}
}
#keyframes animatetop {
from {right:-100px; opacity:0}
to {right:0; opacity:1}
}
<button id="modalbutton" class="modalbutton">Open Modal 1</button>
<button id="modalbutton" class="modalbutton">Open Modal 2</button>
<button id="modalbutton" class="modalbutton">Open Modal 3</button>
<!-- Content 1 -->
<div id="detailmodal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>1 Modal Header</h2>
</div>
<div class="modal-body">
<p>please link with 1</p>
<p>Some other text...</p>
</div>
<div class="modal-footer">
<h3>Modal Footer</h3>
</div>
</div>
</div>
<!-- Content 2 -->
<div id="detailmodal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>2 Modal Header</h2>
</div>
<div class="modal-body">
<p>please link with 2</p>
<p>Some other text...</p>
</div>
<div class="modal-footer">
<h3>Modal Footer</h3>
</div>
</div>
</div>
<!-- Content 3 -->
<div id="detailmodal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>3 Modal Header</h2>
</div>
<div class="modal-body">
<p>please link with 3</p>
<p>Some other text...</p>
</div>
<div class="modal-footer">
<h3>Modal Footer</h3>
</div>
</div>
</div>
You are correct that you don't want to have multiple id's. What you can do is set each button to a different id (modalbutton1, modalbutton2, etc.) Then in javascript get a reference to each button:
var modal1 = document.getElementById('modalbutton1');
var modal2 = document.getElementById('modalbutton2');
Then for each button reference you'll attach an onclick handler
modal1.onclick=function(){ //Write your style code here }
modal2.onclick=function(){ //Write your style code here }
If your html content is static and modal's data isn't dynamic the safe way you can do this is with multiple IDs.I think it's not a good idea to use same id for multiple buttons and div tags.
if the modals div tags wouldn't in the specific order, buttons don't work properly and perhaps it shows the wrong modal.
so it's better to write like this:
btns = document.querySelectorAll('[id*=modalbutton-]');
for (let i = 1; i <= btns.length; i++) {
var modalClassName = 'detailmodal-';
btn = document.getElementById('modalbutton-' + i);
closeBtn = document.querySelector('#' + modalClassName + i + ' .close');
closeBtn.onclick = function() {
modal = document.getElementById(modalClassName + i);
modal.style.display = "none";
}
btn.onclick = function() {
modal = document.getElementById(modalClassName + i);
modal.style.display = "block";
}
}
and html pattern for buttons and modals:
<button id="modalbutton-1" class="modalbutton">Open Modal 1</button>
<div id="detailmodal-1" class="modal">
<button id="modalbutton-2" class="modalbutton">Open Modal 2</button>
<div id="detailmodal-2" class="modal">
If you cant use multiple ids just use data attribute with some value. you can change code above to use attribute and it's value to show a right modal.
<button id="modalbutton" data-button-id="1" class="modalbutton">Open Modal 1</button>
<div id="detailmodal" data-modal-id="1" class="modal">
and change your for loop like this
for (let i = 0; i < btn.length; i++) {
btn[i].onclick = function(event) {
var btnId = event.target.getAttribute("data-button-id");
var modal = document.querySelector("[data-modal-id='" + btnId +"']");
modal.style.display = "block";
}
}
I'm working on a VERY LIGHT survey application. This application runs in third world countries in locations with very limited connection.
We found that the loading-time is proportional to user Engagement (Very important to us).
Today I'm using 2 libs - VueJS and a custom bootstrap build. I would like to invoke a modal. But the modal requires to add the Bootstrap Javascript and the jQuery. those libs almost doubles the loading time.
How can I open a modal without adding those two libs?
#uday's link to CSS only modal is a nice trick, but might be awkward to use if you use #tag's for other purposes (eg, Routing & param passing).
So here is an example that uses very little JS to achieve something very similar. I've tried to keep the Snippet as small as possible so that it's easy to see what's happening.
var modal = document.querySelector(".modal");
var container = modal.querySelector(".container");
document.querySelector("button").addEventListener("click", function (e) {
modal.classList.remove("hidden")
});
document.querySelector(".modal").addEventListener("click", function (e) {
if (e.target !== modal && e.target !== container) return;
modal.classList.add("hidden");
});
.modal {
background-color: rgba(0,0,0,0.4); /* Transparent dimmed overlay */
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: table;
}
.modal.hidden {
display: none;
}
.modal .container {
display: table-cell;
text-align: center;
vertical-align: middle;
width: 200px;
}
.modal .body {
box-shadow: 5px 10px #888888;
display: inline-block;
background-color: white;
border: 1px solid black;
padding: 10px;
}
<button>Show Modal</button>
<div class="modal hidden">
<div class="container">
<div class="body">
<p>Click outside this box to close the modal.<p>
<p>You could of course add a close button etc</p>
<p>But this is left for the OP todo</p>
</div>
</div>
</div>
You don't need any css style. You should create the bootstrap modal in your HTML, then in your js, you have to simply give it some style according to the following description:
var locModal = document.getElementById('locModal');
var btnclose = document.getElementById('w-change-close');
var btnShow= document.getElementById('w-change-location');
//show the modal
btnShow.addEventListener('click', (e) => {
locModal.style.display = "block";
locModal.style.paddingRight = "17px";
locModal.className="modal fade show";
});
//hide the modal
btnclose.addEventListener('click', (e) => {
locModal.style.display = "none";
locModal.className="modal fade";
});
The HTML should be like this:
<!-- Button trigger modal -->
<button id="w-change-location" type="button" class="btn btn-primary mt-3" data-toggle="modal" data-target="#locModal">
Change Location
</button>
<!-- Modal -->
<div class="modal fade" id="locModal" tabindex="-1" role="dialog" aria-labelledby="locModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="locModalLabel">Choose Location</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="" id="w-form">
<div class="form-group">
<label for="city"> City</label>
<input type="text" class="form-control" id="city">
</div>
<div class="form-group">
<label for="state"> State </label>
<input type="text" class="form-control" id="state">
</div>
</form>
</div>
<div class="modal-footer">
<button id="w-change-close" type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="w-change-btn" type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
We write private code for our modal.
let modal = document.getElementById('our-modal');
let modalContentElm = modal.querySelector('.modal-content');
let allModalButtons = modal.querySelectorAll('.modal-footer > .btn');
let outerClick = true;
let openStyle = () => { //MODAL SHOW
modal.style.backgroundColor = 'rgba(0,0,0,0.5)';
modal.style.display = 'block';
setTimeout(() => { modal.style.opacity = 1; }); //FOR TRANSITION
};
let closeStyle = () => { //MODAL HIDE
modal.style.display = 'none';
modal.style.opacity = 0;
};
//NO CLOSE MODAL WHEN YOU CLICK INSIDE MODAL
modalContentElm.onclick = () => {
outerClick = false;
};
//CLOSE MODAL WHEN YOU CLICK OUTSIDE MODAL
modal.onclick = () => {
if(outerClick){ closeStyle(); }
outerClick = true;
};
for(let btn of allModalButtons){
btn.onclick = () => {
closeStyle();
if(btn.getAttribute('id') === 'success-btn'){
//PLEASE WRITE 'success-btn' IN THE ID VALUE OF THE CONFIRM BUTTON
console.log('Click Yes');
}
else{
console.log('Click Cancel');
}
//..... more else if or else for more modal buttons
};
}
Whenever we want to open modal
openStyle();
Whenever we want to close modal on manuel
closeStyle();
It's a bit laborious, but it works. A more general class can be written.
If you are using bootstrap 5, you can easily show and hide modal with js:
Documentation
const myModal = new bootstrap.Modal(document.getElementById('myModal')); // creating modal object
myModal.show(); // show modal
myModal.hide(); // hide modal
If you open the modal using a button. you can add the bootstrap options to that button data-bs-toggle="modal" data-bs-target="#modalTarget" and also a onclick function like onclick="whenOpenModal();"
function whenOpenModal(){
console.log("modal opened");
}
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.
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>