Creating a modal window for images - javascript

So I'm trying to create a modal so that when the user clicks something it will open a modal window of an image. So far I've got a basic one going using a basic script but the way it's done will only allow one to work at a time.
<script>
var modal = document.getElementById("myModal");
var img = document.getElementById("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
modal.style.display = "block";
captionText.innerHTML = modalImg.alt;
}
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
modal.style.display = "none";
}
</script>
This method pretty obviously has the issue of selecting by specfic id. Would there be a way to re-write this so that it takes in the id and etc of whatever is clicked?

HTML:
<div class="modal-container">
<div id="modal" class="modal">
<div class="modal-caption">
<h1>Modal Caption</h1>
</div>
<div id="image" class="image">
<img src="https://images.pexels.com/photos/1079020/pexels-photo-1079020.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" alt="Älter Text">
</div>
<div class="excerpt">
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.</p>
</div>
<div class="close-btn">
<button onclick="closeModal()">Close</button>
</div>
</div>
<div class="call-back-modal">
<button onclick="callModal()">Call Modal</button>
</div>
</div>
CSS:
.modal-container {
width: 100%;
position: relative;
}
.modal-container .modal {
position: absolute;
width: 50%;
top: -700px;
left: 25%;
transition: all 0.4s;
padding: 30px;
border: 1px solid #c3c3c3;
border-radius: 5px;
box-shadow: 0 1px 6px 0 rgba(32, 33, 36, .28);
}
.modal-caption h1 {
margin-top: 0;
}
.modal-container .call-back-modal {
position: relative;
}
#image {
top: -700px;
}
.modal-container .modal img {
width: 100%;
}
JS:
function callModal(){
var modal = document.getElementById("modal");
if (modal.style.top === "0px") {
modal.style.top = "-700px";
} else {
modal.style.top = "0px";
}
}
function closeModal(){
var closeModal = document.getElementById("modal");
modal.style.top = "-700px";
}
Live: Demo

If you mean that you want whenever the user clicks on a certain element, the modal is displayed.
Then instead call a function inline : onclick="displayModal()" for whatever you want to display a modal when it's clicked.
So it will look like this :
function displayModal(){
modal.style.display = "block";
captionText.innerHTML = modalImg.alt;
}

Related

gallery with modal window

I am creating a gallery in PHP. Clicking on each thumbnail should open a modal window with the image and other information.
The problem is that it only works with the first thumbnail and not with the others.
this is part of the php code:
while($i !== $nIMG){
$recordIMG = $q->fetch(PDO::FETCH_ASSOC);
echo "<div class='content-img'><img src='". $recordIMG['urljpg'] ."' id='infoIMG'></div>";
$i++;
}
this is the modal window
<div class="modal" id="myModal">
<img class="modal-content" id="img01">
</div>
this is the javascript code
var modal = document.getElementById("myModal");
var img = document.getElementById("infoIMG");
var modalImg = document.getElementById("img01");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
}
I am thinking it is an ID issue which must be unique. But I don't know how to solve, could someone more experienced help me?
In that case, the php part was okay. Add onclick="openImage(this)" to it, and than move to the javascript part.
There, you would need a new function to pass the image src. I also re-named the modal image class to a more general one: image-content
// Get the modal
var modal = document.getElementById("myModal");
var modalImg = document.getElementById("image-content");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// 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";
}
}
// Look at this code: element is passed to the function
function openImage(element) {
modal.style.display = "block";
// This is where the magic happens :)
modalImg.src = element.src;
}
body {
font-family: Arial, Helvetica, sans-serif;
}
.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;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal -->
<div class='content-img'><img src="https://picsum.photos/100/100?random=1" onclick="openImage(this)"></div>
<div class='content-img'><img src="https://picsum.photos/100/100?random=2" onclick="openImage(this)"></div>
<div class='content-img'><img src="https://picsum.photos/100/100?random=3" onclick="openImage(this)"></div>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content" id="myModal">
<span class="close">×</span>
<img class="modal-content" id="image-content">
</div>
</div>
</body>
</html>
before getting your answer i tried to create two for loops in php and javascript and it works. These are the codes:
PHP:
$n = 0;
for($i = 0; $i !== $nIMG; $i++){
$n++;
$recordIMG = $q->fetch(PDO::FETCH_ASSOC);
echo "<div class='content-img'><img src='". $recordIMG['urljpg'] ."' id='infoIMG".$n."'></div>";
}
Javascript:
var nr = 0;
for(i = 0; i < 100; i++){
nr++;
var y = "infoIMG" + nr;
var img = document.getElementById(y);
var modal = document.getElementById("myModal");
var modalImg = document.getElementById("img01");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
}
}
Everything seems to work fine. Do you think it might be okay or is it better to use the code reported by you?
If I use this code, the only doubt is to understand how to pass the number of rows of the mysql database as the second parameter of the JS for loop.

Javascript how to darken modal backdrop

I'm having trouble darkening the background when I open the modal. I found a ton of info on how to do this with bootstrap, but I am looking for a way to do it using javascript. I currently have the modal opening and closing when I want it to, so I just need to implement the backdrop feature.
HTML
<body>
<h1>Modal</h1>
<button id="myBtn" data-toggle="modal fade" data-target="#myModal">Open Modal</button>
<section class="modal hidden" id="myModal">
<span class="close">×</span>
<h2>I am the modal</h2>
<p>hello world</p>
</section>
</body>
CSS
.modal {
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
border: solid 2px black;
border-radius: 10px;
padding: 30px;
margin: 20px 0;
background-color: greenyellow;
}
.hidden{
display: none;
}
JS
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";
}
}
Any help or starting points on how to implement the backdrop would be appreciated.
You could have a div with the class modalBackdrop to darken the background. You can have it take up the entire page, and give it a color that has transparency like rgba(0,0,0,0.2). You can replace your HTML with the following to add a modal backdrop div element.
<body>
<h1>Modal</h1>
<button id="myBtn" data-toggle="modal fade" data-target="#myModal">Open Modal</button>
<div class="modalBackdrop hidden"></div>
<section class="modal hidden" id="myModal">
<span class="close">×</span>
<h2>I am the modal</h2>
<p>hello world</p>
</section>
</body>
And add the following styles to your CSS for the modal backdrop
.modalBackdrop{
position:fixed;
top:0;
left:0;
width:100vw;
height:100vh;
background-color:rgba(0,0,0,0.2);
}
Finally, replace your JS with the following to show and hide the backdrop when needed
var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
var modalBackdrop = document.getElementsByClassName("modalBackdrop")[0];
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
modalBackdrop.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
modalBackdrop.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
modalBackdrop.style.display = "none";
}
}
Also, making the transparency lower in the CSS will make the background darker when showing the modal.

I am trying to show two different texts in html using a modal view but the javascript overlaps and doesn't work properly

Basically, I have a register page I'm trying to finish and at the checkbox where you agree with terms I have this text
I agree to NAME's "Terms & Conditions" and their "Privacy Policy".
Between the double-quotes there are two separate paragraphs with on click calls to a JavaScript function to two different ".js" files. First one represents the calls and operations made for the first button "Terms & Conditions" and so on. When I try to mix them, they either show the same text, or they don't show anything at all. I will also leave a small bit of code because I believe it's easier to understand my problem.
I've tried mixing them together in a single js files but it worked even worse afterwards. When I take one of the files out, the other works properly.
<label class="auth_margin"><input id="agree" type="checkbox" name="agree"> I agree to NAME's </label><p id="termsBtn"> Terms & Conditions</p> and their <p id="privacyBtn">Privacy Policy.</p><br/>
And the JavaScript files:
var modal = document.getElementById('termsModal');
var btn = document.getElementById("termsBtn");
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 == pmodal) {
pmodal.style.display = "none";
}
}
var pmodal = document.getElementById('privacyModal');
var pbtn = document.getElementById("privacyBtn");
var span = document.getElementsByClassName("close")[0];
pbtn.onclick = function() {
pmodal.style.display = "block";
}
span.onclick = function() {
pmodal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == pmodal) {
pmodal.style.display = "none";
}
}
Does the following code behaves as you expected? You need a single js file for it. There are some style edits, but you can change them afterwards from CSS. Also, I preferred to use <span> instead of <p> for the two click-able texts. The difference is that <p> is a block element and <span> is not. They look nicer on a single line (in my opinion).
Nothing fancy, plain html/css/js.
var tbtn = document.getElementById("termsBtn");
var pbtn = document.getElementById("privacyBtn");
var tmodal = document.getElementById('tmodal');
var pmodal = document.getElementById('pmodal');
tbtn.onclick = function() {
pmodal.style.display = "none";
tmodal.style.display = "block";
};
pbtn.onclick = function() {
tmodal.style.display = "none";
pmodal.style.display = "block";
};
window.onclick = function(event) {
if (event.target == pmodal) {
pmodal.style.display = "none";
} else if (event.target == tmodal) {
tmodal.style.display = "none";
}
}
#termsBtn,
#privacyBtn {
color: blue;
}
/* 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/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto;
/* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%;
/* Could be more or less, depending on screen size */
}
/* 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;
}
<label class="auth_margin"><input id="agree" type="checkbox" name="agree"> I agree to NAME's </label><span id="termsBtn"> Terms & Conditions</span> and their <span id="privacyBtn">Privacy Policy.</span><br/>
<div id="tmodal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Some text for Terms & Conditions</p>
</div>
</div>
<div id="pmodal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Some text for Privacy Policy</p>
</div>
</div>
Cheers!

How Can I Make Popup Blog Content in Wordpress

I want to display my reference works on index. I limited the words. My aim is this: User who wants to learn detail information about post, will click the post thumbnail and the rest of content will open with popup.
I used w3css modal to make it. My javascript codes are:
// 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 on 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";
}
}
But only the first post seems like that. The others have no reaction.
Thanks.
I want to make all thumbnails like that
I made some revision about that. I used fancybox 2 and change my code with this
<?php the_post_thumbnail('thumbnail', array('class' => 'aligncenter')); ?>
<div id="inline1" style="width:400px;display: none;">
<?php the_post_thumbnail('thumbnail', array('class' => 'aligncenter')); ?><?php the_content(); ?>
</div>
Now all the thumbnails open with fancybox but this time the other thumbnails' contents are same with the first post.
I don't think create a modal element in every container is a right way to go.
Instead, I will suggest you make only one modal element, and change the content of
that modal when any image got clicked.
thus, here is a demo that I just made
JSbin
The step will be
find out all container elems
bind those elems with click event
when user click one elem, extract the text and image src of that elem
inject into modal-body
removve hide class
It's fine to have modals mixed in. You have to be a little picky about event handlers and which one to close, but it's not too bad.
var sites = document.querySelectorAll('.site');
var closes = document.querySelectorAll('.close');
var ix;
for (ix = 0; ix < sites.length; ix++) {
sites.item(ix).addEventListener('click', showModal);
}
for (ix = 0; ix < closes.length; ix++) {
closes.item(ix).addEventListener('click', closeModal);
}
function showModal(e) {
e.stopPropagation();
this.querySelector('.modal').style.display = "block";
}
function closeModal(e) {
e.stopPropagation();
try {
getParent(this, 'modal').style.display = "none";
} catch (e) {
console.warn('Failed to find my daddy.');
}
}
function getParent(el, cls) {
while (el.parentElement) {
el = el.parentElement;
if (el.classList.contains(cls)) return el;
}
return null;
}
.site {
display: inline-block;
}
.thumbnail {
width: 100px;
height: 100px;
border: 1px solid black;
margin: 10px;
}
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 50%;
}
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
line-height: 28px;
font-weight: bold;
cursor: pointer;
}
.close:hover,
.close:focus {
color: #000;
}
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<div class="container">
<div class="site">
<div class="thumbnail"></div>
<div class="modal">
<div class="modal-content">
<span class="close">×</span> First Item
</div>
</div>
</div>
<div class="site">
<div class="thumbnail"></div>
<div class="modal">
<div class="modal-content">
<span class="close">×</span> Second Item
</div>
</div>
</div>
</div>

document.getElementById - dynamic use for using the same ID more than once

var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
modalImg.alt = this.alt;
captionText.innerHTML = this.alt;
}
#myImg {
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
}
<img id="myImg" src="imageone.jpg" alt="Image one" >
<br>
<br>
<img id="myImg" src="imagetwo.jpg" alt="Image two" >
So the above snippet is used in the modal image css3 tutorial. I understand i cannot have more than one tags with the same ID which is why the code online works with one image. After researching i know i have to use a dyamic ID with JS.
var img = document.getElementById('myImg');
The previous JS line is what i need to change.
How does one dynamically change getElementById? So that i can use more then one with differentr src images?
Research shows Using a Tag selector or a class selector is inappropriate.
Any help documents to aid in my learning will be great as well.
So i made some nice progress with the css and stuff and it looks great. Now my next step is to use existing alts to include text when the modal appears. Below is the existing js line i had already
var captionText = document.getElementById("caption");
Now below is the html i will use when calling alt so that each image has its own alt text appearing under the modal pop up
I've tried it and doesnt seem to work, could it be my formatting in the css?
If there's a collection of elements that need to be processed the same, it's best to use the class attribute to target them.
Instead of targeting one element with: document.getElementById, you get a NodeList, which is a collection of elements, using document.getElementsByClassName or document.querySelectorAll.
Then, you need to loop through these elements and use the code you've already written.
Here's an example:
var imgs = document.getElementsByClassName('myImg');
for (var i = 0; i < imgs.length; i += 1) {
var img = imgs[i];
img.onclick = function() {
// your on click stuff
};
};
Don't forget to change the HTML to: <img class="myImg" src="imageone.jpg" alt="Image one" >
Hope this is helpful for you
var imgs = document.querySelectorAll('.gallery-img');
if (imgs) {
for (var i = 0; i < imgs.length; i++) {
imgs[i].addEventListener('click', showModal, false);
}
}
function showModal() {
var modal = document.querySelector('.modal');
if (modal) {
var img = modal.querySelector('img');
var close = modal.querySelector('.close');
modal.classList.add('open');
img.src = this.src;
if (close) {
close.addEventListener('click', closeModal, false);
}
}
}
function closeModal() {
this.parentNode.classList.remove('open');
}
img {
width: 200px;
cursor: pointer;
border: 2px solid transparent;
}
img:hover {
border: 2px solid #191919;
}
.modal {
display: none;
width: auto;
height: auto;
background: #ccc;
border-radius: 4px;
padding: 6px;
}
.modal.open {
display: inline-block;
}
.modal .close {
cursor: pointer;
font-size: 16px;
font-weight: bold;
display: block;
text-align: right;
}
<img class='gallery-img' src="http://wallpaperbeta.com/wallpaper/small_fish_by_name_beta_minimalism_hd-wallpaper-296364.jpg" alt="">
<img class='gallery-img' src="https://wallpaperscraft.com/image/flowers_small_flower_surface_rose_43393_2048x1152.jpg" alt="">
<div class="modal">
<span class="close">×</span>
<img src="" alt="">
</div>

Categories

Resources