How to show different <div> in one modal? - javascript

How can i show (toggle) different divs in one modal? Let me explain:
- when i click on "show me more" i wanna trigger modal (and its working in my case)
- next, i close it (it works)
- i wanna trigger modal again but on different div and offcourse i want this div to be in modal again (now thats where i got stuck at).
Below its snippet of my code...
HTML:
<div id="modal" class="modal">
<div class="modal-content">
<span class="close-button">×</span>
<div id="wrapper" class="modified">
<!-- Main -->
<section>
<div class="inner">
<h1 class="major">DJ ZA POROKE</h1>
<p align="justify">some text</p>
<p align="justify">some text</p>
</div>
</section>
</div>
</div>
</div>
JS:
var modal = document.querySelector(".modal");
var trigger1 = document.querySelector(".trigger1");
var closeButton = document.querySelector(".close-button");
function toggleModal() {
modal.classList.toggle("show-modal");
}
function windowOnClick(event) {
if (event.target === modal) {
toggleModal();
}
}
trigger1.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
And lets say i trigger it like:
<div class="middle">
<div class="text trigger">Show me more..</div>
Thanks for your help.
Regards.

So to get it right:.
user clicks a button /other element ("show me more") and a
modal is shown with content 1
modal is closed
user clicks again a button /other element ("show me more") and a
modal is shown with content 2.
modal is closed
You have 2 options:
call two different modals identical except for the content -> this can be done with a state var in JS
var stateContent = 0;
and check on the button click event in which state we are
The second more elegant shows/hides the relevant div
HTML addapted
<div id="modal" class="modal">
<div class="modal-content">
<span class="close-button">×</span>
<div id="wrapper" class="modified">
<!-- Main -->
<section>
<div id="content_1" class="inner" style="display: block"> <!-- ID added This part is shown -->
<h1 class="major">DJ ZA POROKE</h1>
<p align="justify">some text</p>
<p align="justify">some text</p>
</div>
<div id="content_2" class="inner" style="display: none"> <!-- ID added This part is hidden -->
<h1 class="major">XY ZZ POROKE</h1>
<p align="justify">some OTHER text</p>
<p align="justify">some OTHER text</p>
</div>
</section>
</div>
</div>
</div>
In javascript you change the display style - for simplification I do it on the close button
closeButton.addEventListener("click", function(e){
switchContent();
toggleModal();
});
New function for doing what we want content switching:
function switchContent(){
var content1 = document.getElementById("content_1");
var content2 = document.getElementById("content_2");
// Check in which state we are
if (content1.style.display === 'none') {
content1.style.display = 'block';
content2.style.display = 'none';
}
else {
content1.style.display = 'none';
content2.style.display = 'block';
}
}

I just opened editor at w3 so i can show directly what i want:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* 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: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* 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>
</head>
<body>
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<button id="myBtn2">Open Modal2</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..1</p>
</div>
</div>
<!-- The Modal -->
<div id="myModal2" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..2</p>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById("myModal");
var modal2 = document.getElementById("myModal2");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
var btn2 = document.getElementById("myBtn2");
// 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";
}
btn2.onclick = function() {
modal2.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
span.onclick = function() {
modal2.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";
}
if (event.target == modal2) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
So you see something went wrong, because when i click OPENMODAL2 it freezes. But anyhow, i want 8 different divs to show in 1 modal.

Related

How to open a modal with Javascript when an image box is clicked and it closes when clicked outside the box?

I have created a modals with Javascript. For now when I click the image the modal opens and when I click on cross button it closes. What I want is instead of picture when user clicks on image box not on specifically image, the modal should open and when user clicks outside modal box anywhere it should close not only with cross button.
Html:
<section id="about-intro">
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-sm-12 col-lg-11 about-start">
<div class="about-content">
<div class="about-box">
<div class="upp-title">
<div class="upp-headshot">
<picture> <img src="image"
href="#myModal1" class="rounded-circle" alt="Responsive image"/> </picture>
</div>
<div class="upp-info">
<h3><span class="about-name">abc</span>
</h3>
<p><span class="about-des">xyz</span></p>
</div>
</div>
<!-- The Modal -->
<div id="myModal1" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12" style="text-align: center;">
<img src="" class="img-
fluid" alt="Responsive image">
</div>
<div class="col-md-12" style="text-align: center;">
<h1 class="modalh1">abc</h1>
<h3 class="modalh3">xyz</h3>
<p class="modalp">qwertyuicffvgbhnmghj</p>
</div>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
Script:
<script>
// Get the button that opens the modal
var img = document.querySelectorAll("img.rounded-circle");
// All page modals
var modals = document.querySelectorAll('.modal');
// Get the <span> element that closes the modal
var spans = document.getElementsByClassName("close");
// When the user clicks the button, open the modal
for (var i = 0; i < img.length; i++) {
img[i].onclick = function(e) {
e.preventDefault();
modal = document.querySelector(e.target.getAttribute("href"));
modal.style.display = "contents";
}
}
// When the user clicks on <span> (x), close the modal
for (var i = 0; i < spans.length; i++) {
spans[i].onclick = function() {
for (var index in modals) {
if (typeof modals[index].style !== 'undefined') modals[index].style.display = "none";
}
}
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target.classList.contains('modal')) {
for (var index in modals) {
if (typeof modals[index].style !== 'undefined') modals[index].style.display = "none";
}
}
}
</script>
Hope it helps.
I always use flex display so I can click the external content.
I tried to insert it to your code
Change style of .modal
<div
id="myModal1"
class="modal"
style="
display: none;
width: 100vw;
height: 100vh;
justify-content: center;
align-items: center;
position: fixed;
top: 0px;
left: 0px;
">
then in js, instead of window.onclick
for (var i = 0; i < modals.length; i++) {
modals[i].onclick = function (event) {
if (!event.target.closest('.modal-content')) {
for (var index in modals) {
if (typeof modals[index].style !== 'undefined')
modals[index].style.display = 'none';
}
}
};
}
You can change selector to .upp-title or .upp-headshot for a bigger clickable area.
I Hope You Can Use this method to your code! Check this out
document.addEventListener(
"click",
function(event) {
// If user either clicks X button OR clicks outside the modal window, then close modal by calling closeModal()
if (
event.target.matches(".button-close-modal") ||
!event.target.closest(".modal")
) {
closeModal()
}
},
false
)
function closeModal() {
document.querySelector(".modal").style.display = "none"
}
.modal {
padding: 2rem;
border: 1px solid #eee;
width: max-content;
position: fixed;
right: 0;
bottom: 0;
max-width: 100%;
}
.button-close-modal {
display: block;
font-size: 2rem;
font-weight: bold;
margin-left: auto;
}
<main>
<div class="modal">
<button class="button-close-modal">X</button>
<h2>Modal close without Using button(X)</h2>
<p>Sed ut perspiciatis unde voluptatem accusantium doloremque laudantium,</p>
<label for="email">Enter your email:</label>
<input type="email" id="email" name="email">
</div>
</main>

how do i open modal with javascript. without using jquery

How do I make a modal visible with javascript? I don't want to do it using jquery. i just want it with javascript. And I don't want it to open when I click a button. I want it to be opened as a result of some operations in javascript. I made it with modal bootstrap. my codes are below.
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Document</title>
</head>
<body>
<div class="modal fade" tabindex="-1" id="sonucModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Test Durumu</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p id="durum"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Çıkış</button>
<button type="button" class="btn btn-primary">2. Aşamaya Geç</button>
</div>
</div>
</div>
</div>
<div class="container" style="height: 100vh;">
<div class="row" style="height: 100vh;">
<div class="col-md-12 d-flex justify-content-center" style="height: 400px;">
<div class="card" style="width: 25rem; margin-top:20vh; ">
<div class="card-body" style="text-align: center;">
<h5 class="card-title text-primary">Soru</h5>
<span class="text-black-50 fs-5" id="soru"></span>
<input class="w-100 form-control mt-4" type="text" id="cevap"/>
<button class="btn btn-outline-primary mt-4 w-100" id="ok">Tamam</button>
</div>
<ul class="list-group list-group-flush">
<li id="anaCan" class="list-group-item fw-bold">Kalan Can: <span id="can"></span></li>
</ul>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
javascript code:
var turkceCumleler = [
"Merhaba",
"İyi Sabahlar",
"İyi Günler",
"İyi Akşamlar",
"İyi Geceler",
"Tekrar Görüşmek Üzere(Yüz yüze)",
"Tekrar Görüşmek Üzere(Tel.)",
"Yakında Görüşürüz",
"Güle Güle"
];
var almancaCumleler = [
"hallo",
"guten morgen",
"guten tag",
"guten abend",
"gute nacht",
"auf wiedersehen",
"auf wiederhögen",
"bis bald",
"tschüss"
]
var sayilar = [];
var healt = 3;
const getQuestion = () =>{
document.getElementById('can').textContent=healt;
let rastgele = Math.floor(Math.random()*turkceCumleler.length);
if(sayilar.indexOf(rastgele) === -1){
sayilar.push(rastgele)
document.getElementById('soru').textContent = turkceCumleler[rastgele];
document.getElementById('cevap').value = ""
}else{
getQuestion();
}
if(sayilar.length === turkceCumleler.length){
//here i want modal to open
}
}
const compareQuestionAnswer = () =>{
if(document.getElementById('cevap').value === ''){
alert("boş geçilemez")
}else{
let deger = almancaCumleler.indexOf(document.getElementById('cevap').value.toLowerCase());
if(deger === -1){
healt--;
document.getElementById('can').textContent=healt;
if(healt === 0){
document.getElementById('anaCan').style.color='red';
document.getElementById('ok').disabled = true;
}
}else{
let deger1 = turkceCumleler.indexOf(document.getElementById('soru').textContent);
if(deger === deger1){
getQuestion();
}else{
healt--;
document.getElementById('can').textContent=healt;
if(healt === 0){
document.getElementById('anaCan').style.color='red';
document.getElementById('ok').disabled = true;
}
}
}
}
}
window.onload = getQuestion;
document.getElementById('ok').addEventListener('click',compareQuestionAnswer);
document.getElementById('anaCan').style.color='green';
Bootstrap depends on jQuery, and you're already including jQuery in your code.
But if you want to create a modal without Bootstrap and jQuery, you can do so with CSS and JavaScript. Use an event listener to listen for whatever JavaScript event you desire, then show the modal when that event occurs.
Here is a simple example:
// Show the modal when you hover over the red box
trigger.onmouseover = () => {
modal.style.display = "block";
}
// Hide the modal when you click the close button
document.getElementsByClassName("close")[0].onclick = () => {
modal.style.display = "none";
}
// Hide the modal if you click outside of the modal area
window.onclick = (event) => {
if (event.target == modal) {
modal.style.display = "none";
}
}
#trigger {
height: 100px;
width: 100px;
background-color: red;
}
.modal {
display: none; /* Hidden Initially */
position: fixed;
z-index: 1; /* Higher Z-Index To Sit On Top */
left: 0;
top: 0;
width: 100%; /* Full Width */
height: 100%; /* Full Height */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<div id="modal" class="modal">
<!-- Modal Content -->
<div class="modal-content">
<span class="close">x</span>
<p>Modal content here</p>
</div>
</div>
<div id="trigger">
Move mouse into this box to trigger modal.
</div>
You just need to declare a new modal object, like:
const sonucModal= document.getElementById('sonucModal');
const modalEl = new bootstrap.Modal(sonucModal);
and then call it like this whenever you need to open it:
modalEl.show();
Here is a JSFiddle for reference, the modal opens automatically after 2 seconds.

Generating unique modals for each element in php

I have this project where the user selects an item from a list (fetched from a MySQL database), then outputs buttons named from the item
as such:
My (stripped down) code so far:
<!DOCTYPE html>
<html>
</head>
<body>
<h2>Select User:</h2>
<div>
<form method="POST">
<table border="5">
<thead>
<th></th>
<th>Subject</th>
</thead>
<tbody>
<?php
include('get.php');
$query=mysqli_query($conn,"select * from `subjects`");
while($row=mysqli_fetch_array($query)){
?>
<tr>
<td><input type="checkbox" value="<?php echo $row['subject']; ?>" name="id[]"></td>
<td><?php echo $row['subject']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
<div>
<h2>Subjects selected:</h2>
<?php
if (isset($_POST['submit'])){
foreach ($_POST['id'] as $id):
$sq=mysqli_query($conn,"select * from `subjects` where subject='$id'");
$srow=mysqli_fetch_array($sq);
?>
<button class="button animate" id="myBtn">
<span>
<?php echo $srow['subject']; ?>
</span>
</button>
<?php
endforeach;
}
?>
</div>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
<script>
var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[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>
I was able to make a modal for one button but I want to make a unique modal for each button. How can I do this? Thanks.
Write a function which will build a modal for you. Have this function accept some input, like the content of the modal which you want to show. Then add the modal to the page. This way you can generate an infinite amount of different modals based on the button that you click on.
I've made an example below which demonstrates how this could work. The example works with building a modal, with the same structure of your example, and use the value attribute of the button the set the content of that modal. For simple text this works fine, but for larges chunks of HTML you might consider getting your content from a hidden element and copy the innerHTML value of that element.
// Flag for checking if a modal is already opened.
// This way we can keep track of the opened modal and
// not open a second one before closing the first.
let modalOpen = false;
function createModal(html = '') {
// Create the elements.
const modal = document.createElement('div');
const content = document.createElement('div');
const close = document.createElement('span');
// Add classes to the elements.
modal.classList.add('modal');
content.classList.add('modal-content');
close.classList.add('close', 'js-close-modal');
// Add content to the elements.
content.insertAdjacentHTML('beforeend', html);
close.innerHTML = '×';
// Append children to parents and to the document.
content.appendChild(close);
modal.appendChild(content);
document.body.appendChild(modal);
return modal;
}
// Listen for clicks in the document.
document.addEventListener('click', event => {
// If the create modal button has been clicked, create a modal.
const button = event.target.closest('.js-create-modal');
if (button !== null && modalOpen === false) {
const html = button.value;
createModal(html);
modalOpen = true;
}
// If the close modal has been clicked, remove the modal.
const close = event.target.closest('.js-close-modal');
if (close !== null) {
const modal = close.closest('.modal');
modal.remove();
modalOpen = false;
}
});
*, *::before, *::after {
box-sizing: border-box;
}
.modal {
display: block;
position: fixed;
top: 50%;
left: 50%;
width: 100%;
height: 90%;
max-width: 32em;
max-height: 48em;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.25);
padding: 15px;
transform: translate(-50%, -50%);
background: #ffffff;
border: 1px solid #d0d0d0;
border-radius: 5px;
z-index: 99;
}
.modal-content {
padding: 15px;
}
.close {
position: absolute;
top: 15px;
right: 15px;
cursor: pointer;
}
<button class="js-create-modal" value="This is my first modal.">Modal 1</button>
<button class="js-create-modal" value="All the modals have their own content.">Modal 2</button>
<button class="js-create-modal" value="And are unique in every way.">Modal 3</button>
Another way would be to have a single modal on the page, which you show and hide. Whenever you click a button, you should modify the content of the modal based on the button that you clicked. That way you only have to modify a single piece. But hey, if a modal is hidden, why not just remove it and build a new one when you need it? Your choice.

Displaying show/hide content with a button and an .active css class

I am trying to create a testimonial section on a wordpress site where there is an "expand" button to show the full testimonial quote. I want the text in the button to change to "collapse" after it is clicked. I also need to add a class to the div wraper so I can implement custom css styling when the button is active. I need this pasted three times. The problem is it fails after the first testimonial.
I have this working with the code below, with it duplicated three times (for three different testimonials) and it works on a basic html document. But when I implement it in a wordpress site by pasting the code, only the first testimonial totally works. The other two do show/hide my inner div element, but they won't insert the .active class or change the text of the button to "collapse"
Both of the second testimonials give a
"Uncaught TypeError: Cannot set property 'innerHTML' of null" in the console.
So for example, here are two out of three of my testimonials I want to show. I have to change the ID's on them to avoid the javascript conflict.
function showhide() {
var content = document.getElementById('hidden-content');
var wrap = document.getElementById('testimonial-wrap');
var btn = document.getElementById('button1');
if (content.style.display === 'none') {
content.style.display = 'block';
wrap.style.background = 'grey';
btn.innerHTML = 'COLLAPSE';
wrap.classList.add('active');
} else {
content.style.display = 'none';
wrap.style.background = 'white';
btn.innerHTML = 'EXPAND';
wrap.classList.remove('active');
}
}
function showhide2() {
var content2 = document.getElementById('hidden-content2');
var wrap2 = document.getElementById('testimonial-wrap2');
var btn2 = document.getElementById('button2');
if (content2.style.display === 'none') {
content2.style.display = 'block';
wrap2.style.background = 'grey';
btn2.innerHTML = 'COLLAPSE';
wrap2.classList.add('active');
} else {
content2.style.display = 'none';
wrap2.style.background = 'white';
btn2.innerHTML = 'EXPAND';
wrap2.classList.remove('active');
}
}
<div id="testimonial-wrap" style="background-color: white;">
<div id="testimonial">
above testimonial content
<div id="hidden-content" style="display: none;">
<p>"hidden content”</p>
</div>
<button id="button1" onclick="showhide()">EXPAND</button>
</div>
</div>
<div id="testimonial-wrap2" style="background-color: white;">
<div id="testimonial">
above testimonial content
<div id="hidden-content2" style="display: none;">
<p>"hidden content.”</p>
</div>
<button id="button2" onclick="showhide2()">EXPAND</button>
</div>
</div>
I think this is what you're looking for. You can do it much easier with jQuery & a small amout of code.
I didn't use display: none as I want to add the transition to the action. (transition won't work with display: none)
$(document).ready(function() {
$(".toggle-button").on("click", function() {
$(this).closest(".testimonial-wrap").toggleClass("active");
});
});
.testimonial-wrap {
background-color: #C1C1C1;
padding: 5px;
margin-bottom: 10px;
}
.testimonial-wrap.active {
background-color: #0095FF
}
.hidden-content {
height: 0px;
visibility: hidden;
transition: all 0.5s ease-out;
}
.active .hidden-content {
height: 100px;
visibility: visible;
transition: all 0.5s ease-in;
background-color: rgba(0, 0, 0, 0.5);
}
button {
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="testimonial-wrap">
<div id="testimonial">
<p>above testimonial content</p>
<div class="hidden-content">
<p>"hidden content”</p>
</div>
<button id="button1" class="toggle-button">EXPAND</button>
</div>
</div>
<div class="testimonial-wrap">
<div id="testimonial">
<p>above testimonial content</p>
<div class="hidden-content">
<p>"hidden content.”</p>
</div>
<button id="button2" class="toggle-button">EXPAND</button>
</div>
</div>

opening multiple modals with one function

I have pictures with "learn more" button underneath. I'm trying to figure out how to write the js with each button showing different modal content.
var modal = document.getElementsByClassName("myModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[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";
}
};
html looks like:
<div class="gallery">
<h3>Bobcats</h3>
<img/>
<button id="myBtn">Learn More</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>
</p>
</div></div>
I have 5 sections that need to be shown. Each additional section looks like the one above. I know the buttons need a unique id and I think setting up the class is where I'm running into trouble.
First of all you can't repeat ID's in a page ... they are unique by definition.
Use classes and loop over the class collection to deal with instances, something like:
// collection of galleries
var galleries = document.getElementsByClassName('gallery');
// iterate galleries collection
for (var i = 0; i < galleries.length; i++) {
let gal = galleries[i], // specific gallery instance
modal = gal.querySelector('.modal'), // modal within this gallery instance
learnBtn = gal.querySelector('.learn');//button within this gallery instance
let toggleModal = function(){
modal.classList.toggle('show');
};
learnBtn.onclick = modal.onclick = toggleModal;
}
.modal {
display: none;
}
.modal.show {
display: block;
background: #eaeaea;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0
}
.modal-content {
background: white;
border: 3px solid #ccc;
margin: 20%;
padding:30px;
}
<div class="gallery">
<h3>Gallery 1</h3>
<button class="learn">Learn More</button>
<div class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Gallery 1 modal
</p>
</div>
</div>
</div>
<div class="gallery">
<h3>Gallery 2</h3>
<button class="learn">Learn More</button>
<div class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Gallery 2 modal
</p>
</div>
</div>
</div>

Categories