Two modals with different ID show the same content - javascript

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);

Related

Link specific button with specific modal

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";
}
}

How to open a Bootstrap modal without jQuery or bootstrap.js javascript?

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");
}

Javascript: I have multiple trigger button on a page, but they all trigger the last event

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.

Multiple buttons only opening most recent modal in code

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];

Multiple Modals, Can't Close?

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">&times</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>

Categories

Resources