How can I create a set of modals? - javascript

I want to create multiple buttons and each button opens a different modal using the logic of the code below, or another similar way to achieve this.
I don't want to use any libraries or frameworks, just vanilla Javascript.
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// 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";
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
</body>
</html>

You can try this way
// Get the modal
var modal = document.getElementsByName("modal");
function openmodal(id) {
document.getElementById(id).style.display = "block";
}
function closemodal(id) {
document.getElementById(id).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";
}
}
.modal{
display:none;}
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal -->
<button onclick="openmodal('myModal')"> Open Modal</button>
<button onclick="openmodal('myModal2')"> Open Modal2</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close" onclick="closemodal('myModal')">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
<!-- The Modal -->
<div id="myModal2" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close" onclick="closemodal('myModal2')">×</span>
<p>Some text in the Modal222</p>
</div>
</div>

Related

Bootstrap5 modal must toggle visibility of divs

What specific changes need to be made in the Bootstrap 5 example below in order for the following two things to occur:
the "afterAcceptingTerms" div should be hidden until the user has clicked on the Accept Terms modal button, so that only the "beforeAcceptingTerms" div should be visible until the user has clicked on the Accept Terms modal button.**
the "afterAcceptingTerms" should become visible once the user clicks on the Accept Terms modal button, and the "beforeAcceptingTerms" div should be hidden once the user clicks on the Accept Terms modal button.
Here is the Bootstrap 5 code we are currently starting with, but you can see that the code example below fails to toggle the
div classes as stated in the requirements above.
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>Modal Popup Page</title>
<link href="/assets/css/bootstrap.min.css" rel="stylesheet">
<script src="/assets/js/popper.min.js"></script>
<script src="/assets/js/bootstrap.min.js" ></script>
</head>
<body>
<div class="wrapper" id="beforeAcceptingTerms">
<section class="content-section">
<p>You must click on the "I agree to the terms button" in order to see the content on this page.</p>
</section>
</div>
<div class="wrapper" id="afterAcceptingTerms">
<section class="content-section">
<p>The page content goes here. But this is only visible because you clicked on the Accept button on the modal in order to get the modal to go away.</p>
</section>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" data-bs-backdrop="static" aria-hidden="true">
<div class="modal-dialog" style="position: fixed;bottom: 0;left: 0;right: 0;">
<div class="modal-content">
<div class="modal-body">
By using this site, you certify that you agree to our Terms of Use.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" onclick="localStorage.setItem('acceptTerms',1)">I agree to the Terms.</button>
</div>
</div>
</div>
</div>
<script>
let acceptTerms = localStorage.getItem('acceptTerms');
if(acceptTerms != 1){
var myModal = new bootstrap.Modal(document.getElementById('myModal'), {})
myModal.show()
}
</script>
</body>
</html>
You forgot to add CDNs instead your local files.
(I added a button to clear local storage data for testing purpose).
What did I change?
// Window onload event to display your content if users has accepted terms
// calling checkTerms() function
window.onload = (event) => {
checkTerms();
};
const afterAcceptingTerms = document.getElementById('afterAcceptingTerms');
const acceptTermsButton = document.getElementById('acceptTermsButton');
// Added a listener to your accept terms button
// removing inline onclick element attribute
acceptTermsButton.addEventListener('click', function() {
termsAccepted();
});
// Here we manage what to do when user click in the accept terms button
// in this case with try/catch to prevent critical errors its good to send
// errors like that (in a catch block) to a server for you stay on what errors users can experience
function termsAccepted() {
try {
localStorage.setItem('acceptTerms',1);
} catch (error) {
alert('CRITICAL ERROR !!!! USER WILL NOT SEE THE CONTENT');
}
afterAcceptingTerms.classList.remove('none');
}
// Function called when window load !! To check if user has accept the terms !
// I'm using try/catch because this is critical, if the localStorage can't be accessed
// your content won't be shown
function checkTerms() {
let val = '';
try {
val = localStorage.getItem('acceptTerms');
} catch (error) {
alert('CRITICAL ERROR !!!! USER WILL NOT SEE THE CONTENT');
}
if (val === '1') {
afterAcceptingTerms.classList.remove('none');
} else {
var myModal = new bootstrap.Modal(document.getElementById('myModal'), {})
myModal.show()
}
}
Also added a .none class with (display:none) to your #afterAcceptingTerms element, it was essential this element starts with display:none. We are going to remove that class programmatically:
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>Modal Popup Page</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<style>
.none {
display: none;
}
</style>
</head>
<body>
<div class="wrapper" id="beforeAcceptingTerms">
<section class="content-section">
<p>You must click on the "I agree to the terms button" in order to see the content on this page.</p>
</section>
<button id="clearData">Clear storage data</button>
</div>
<div class="wrapper none" id="afterAcceptingTerms">
<section class="content-section">
<p>The page content goes here. But this is only visible because you clicked on the Accept button on the modal in order to get the modal to go away.</p>
</section>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" data-bs-backdrop="static" aria-hidden="true">
<div class="modal-dialog" style="position: fixed;bottom: 0;left: 0;right: 0;">
<div class="modal-content">
<div class="modal-body">
By using this site, you certify that you agree to our Terms of Use.
</div>
<div class="modal-footer">
<button type="button" id="acceptTermsButton" class="btn btn-secondary" data-bs-dismiss="modal">I agree to the Terms.</button>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script>
var clearData = document.getElementById('clearData');
clearData.addEventListener('click', function() {
localStorage.clear();
});
window.onload = (event) => {
checkTerms();
};
const afterAcceptingTerms = document.getElementById('afterAcceptingTerms');
const acceptTermsButton = document.getElementById('acceptTermsButton');
acceptTermsButton.addEventListener('click', function() {
termsAccepted();
});
function termsAccepted() {
try {
localStorage.setItem('acceptTerms',1);
afterAcceptingTerms.classList.remove('none');
} catch (error) {
alert('CRITICAL ERROR !!!! USER WILL NOT SEE THE CONTENT');
}
}
function checkTerms() {
let val = '';
try {
val = localStorage.getItem('acceptTerms');
if (val === '1') {
afterAcceptingTerms.classList.remove('none');
} else {
var myModal = new bootstrap.Modal(document.getElementById('myModal'), {})
myModal.show()
}
} catch (error) {
alert('CRITICAL ERROR !!!! USER WILL NOT SEE THE CONTENT');
}
}
</script>
</body>
</html>

How to hide Bootstrap 5 modal on button click

I have a Bootstrap 5 modal, which is used to download a file by clicking a button. This works fine, but I want the modal to be hidden after clicking the download button, and this is where I'm struggling.
I am attempting to use jQuery to do this. I know that the jQuery library is successfully imported and that my function is being executed because I can display an alert box within the same function, but I can't get the modal to hide.
The full code snippet is pasted below with the script section at the bottom. The key line of code that I am trying to use to dismiss the modal is: -
$('#downloadConfirm1').modal({show : false});
I have also tried the following: -
$('.modal.in').modal('hide');
But neither has worked. I am extremely grateful to anyone who takes the time to read my post. Any suggestions most welcome!
<!DOCTYPE html>
<html>
<head lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Java Documentum Services</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.min.js" integrity="sha512-OvBgP9A2JBgiRad/mM36mkzXSXaJE9BEIENnVEmeZdITvwT09xnxLtT4twkCa8m/loMbPHsvPl0T8lRGVBwjlQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" integrity="sha512-GQGU0fMMi238uA+a/bdWJfpUGKUkBdgfFdgBm72SUQ6BeyWjoY/ton0tEjH+OSH9iP4Dfh+7HM0I9f5eR0L/4w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<div class="container">
<a class="btn btn-sm btn-outline-primary" data-bs-toggle="modal"
data-bs-target="#downloadConfirm1"
role="button">Download
</a>
<div class="modal fade" id="downloadConfirm1" tabindex="-1" aria-labelledby="downloadConfirm1"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="downloadModalLabel">Confirm download</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"
aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Download Docx_test_file.docx?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<a href="files/dummy.pdf" download="dummy.pdf">
<button type="button" id="download_button1">Download</button>
</a>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
$('#download_button1').click(function() {
alert("Hello! I am an alert box!!");
$('#downloadConfirm1').modal({show : false});
});
</script>
</html>
Bootstrap 5 modal dropped jQuery so that is why you cannot hide the modal with jQuery. You should save your modal instance in the moment of initialization.
Afterwards you can use this code to hide your modal.
Ref: Bootstrap 5 Modal#hide
var modalInstance = new bootstrap.Modal(document.getElementById('downloadConfirm1'));
var modal = document.getElementById('downloadConfirm1');
modalInstance.hide(modal);
var myModalEl = document.querySelector('#scheduleMeetingModal');
var myModal = bootstrap.Modal.getOrCreateInstance(myModalEl);
myModal.hide();

Modal close on submit

I have this modal window that pops up when you open a page. I have problems closing it after submitting a form. It closes with a button and when you click outside it, but somehow I can't close it with a submit button.
My scripts
var modal = document.getElementById('myModal');
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
The button I want to close the modal with.
<input type="submit" name="submit" value="Send" > </form>
use elem.modal()
$('#myModal').modal('hide')
Bootstrap need a jquery .so better do with jquery function
$(document).ready(function() {
$('#myModal').modal('show')
$('form').on('submit', function(e) {
e.preventDefault();
$('#myModal').modal('hide')
})
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Modal Methods</h4>
</div>
<div class="modal-body">
<form>
<input type="submit" name="submit" value="Send"> </form>
</div>
</div>
</div>
</div>

more than 2 model in same page

In the examples above, i use a button to close the modal. However, with a little bit of JavaScript, you can also close the modal when clicking outside of the modal box.
the problem is when i use 2 modals just i can close first modal when i click any where , the second one i cannot !!
<!DOCTYPE html>
<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
<button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Open Modal 1</button>
<button onclick="document.getElementById('id02').style.display='block'" class="w3-button w3-black">Open Modal 2</button>
<div id="id01" class="w3-modal">
<div class="w3-modal-content w3-card-4">
<div class="w3-container">
<p>model 1</p>
</div>
</div>
</div>
<div id="id02" class="w3-modal">
<div class="w3-modal-content w3-card-4">
<div class="w3-container">
<p>model 2</p>
</div>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('id01','id02');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
The function document.getElementById, just like the Element in the name indicates, only gets one element, so the second parameter, 'id2', is ignored, and you end up only getting the first modal element. Read more in the document.
You can use document.getElementsByClassName to fix this:
<!DOCTYPE html>
<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
<button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Open Modal 1</button>
<button onclick="document.getElementById('id02').style.display='block'" class="w3-button w3-black">Open Modal 2</button>
<div id="id01" class="w3-modal">
<div class="w3-modal-content w3-card-4">
<div class="w3-container">
<p>model 1</p>
</div>
</div>
</div>
<div id="id02" class="w3-modal">
<div class="w3-modal-content w3-card-4">
<div class="w3-container">
<p>model 2</p>
</div>
</div>
</div>
<script>
// Get the modal
var modals = document.getElementsByClassName('w3-modal');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
console.log(event.target, event.target == modals[0], event.target == modals[1]);
if (event.target == modals[0] || event.target == modals[1]) {
modals[0].style.display = "none";
modals[1].style.display = "none";
}
}
</script>
</body>
</html>
Optionally, you can use a relatively new api, document.querySelector, to unify the usages of selecting DOM elements. It uses css selector like string to select elements. But it's a bit new so you may want to check browser compatibility before using it.

How to detect a page is reloaded by anchor tag or not?

I have a page (index.html) and it is looks like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<a href="index.html" target="_top" >reload</a>
</body>
</html>
When a user clicks on anchor tag then index.html reload due to the same reference of the page href="index.html".
So, is there any way to check whether a user clicks on anchor tag or reload by another way like by pressing F5 Key or pragmatically (window.location.reload()).
Edit:
window.onbeforeunload = function(){
// how to capture here
}
As for window.onbeforeunload you can do this:
window.onbeforeunload = function(e) {
e = e || window.event;
e.preventDefault = true;
e.cancelBubble = true;
e.returnValue = 'test';
}
As for Bootstrap and FontAwesome try:
CSS:
<!-- Modal -->
<div id="modalId" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"><span>Page Loader</span></h4>
</div>
<div class="modal-body">
<p>Please wait...</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JavaScript:
window.onbeforeunload = function(e) {
e = e || window.event;
e.preventDefault = true;
e.cancelBubble = true;
$('.modal-body').append('<span class="fa fa-spinner fa-spin" aria-hidden="true"></span>')
$('#modalId').modal('show');
};

Categories