This question already has an answer here:
How to understand `this` inside a normal function and an arrow function?
(1 answer)
Closed 3 years ago.
I'm building a modal based off of w3s's tutorial however, instead of grabbing an "id" I need to grab multiple images with a "class" name instead. I used the classic for loop method then added a click function which does pop up with an empty box.
The problem is, although the box and background style appears the image is not showing up. Using an "id" on the target image + without the for loop works fine, shows up but adding a "class" with the loop does not. There's something I am missing in JS. Any help would be appreciated.
let modal = document.getElementById("modal");
let imgs = document.getElementsByClassName("images");
let modalImg = document.getElementById("modal-img");
for (let i = 0; i < imgs.length; i++) {
imgs[i].addEventListener("click", () => {
modal.style.display = "block";
modalImg.src = this.src;
});
}
.images {
border-radius: 5px;
cursor: pointer;
}
.modal {
display: none;
position: fixed;
z-index: 999;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden;
background-color: rgba(0, 0, 0, 0.7);
}
.modal-content {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}
<!-- target images -->
<div>
<img src="https://via.placeholder.com/150?text=image1" alt="" class="images">
</div>
<div>
<img src="https://via.placeholder.com/150?text=image2" alt="" class="images">
</div>
<!-- modal -->
<div id="modal" class="modal">
<img class="modal-content" id="modal-img">
</div>
An Arrow function () => doesn't bind it's own this - You'll have to use standard function expression to bind this to the correct context ( The element in this case )
let modal = document.getElementById("modal");
let imgs = document.getElementsByClassName("images");
let modalImg = document.getElementById("modal-img");
for (let i = 0; i < imgs.length; i++) {
imgs[i].addEventListener("click", function () {
modal.style.display = "block";
modalImg.src = this.src;
});
}
.images {
border-radius: 5px;
cursor: pointer;
}
.modal {
display: none;
position: fixed;
z-index: 999;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden;
background-color: rgba(0, 0, 0, 0.7);
}
.modal-content {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}
<div>
<img src="https://placekitten.com/150?image=1" alt="" class="images">
</div>
<div>
<img src="https://placekitten.com/150?image=2" alt="" class="images">
</div>
<div id="modal" class="modal">
<img class="modal-content" id="modal-img">
</div>
Related
I'm not well versed in JavaScript, so I'm probably not explaining this right, but I have a jsfiddle. I have a script that pops up a modal with another page in it. If I'm using one link all is well and everything works. It's perfect for what I need.
There are times when I want to add a second link with the same ID so that it pops up with the same functionality, same page and everything, but when I do that only the first link on the page works and the second link fails.
If I remove the first link, the second one works fine.
I would appreciate any thoughts on how to fix this so they both work.
HTML:
<p>
<a href="" id="link"
>Add your thoughts (this works, but the second link doesn't unless this
one is removed).</a
>
</p>
View or Add Comments<br />
<div id="popup"><iframe id="popupiframe"></iframe></div>
<div id="popupdarkbg"></div>
<p>(Click background to exit popup)</p>
JavaScript:
document.getElementById("link").onclick = function (e) {
e.preventDefault();
document.getElementById("popupiframe").src = "http://www.blankwebsite.com/"
document.getElementById("popup").style.display = "block";
document.getElementById("popupiframe").src =
"http://www.blankwebsite.com/";
document.getElementById("popupdarkbg").onclick = function () {
document.getElementById("popup").style.display = "none";
document.getElementById("popupdarkbg").style.display = "none";
};
CSS:
#comments {
width: 100%;
text-align: center;
margin: 15px 0 15px 0;
}
#popup {
display: none;
position: fixed;
top: 12%;
left: 15%;
width: 70%;
height: 80%;
background-color: white;
z-index: 10;
}
#popup iframe {
width: 100%;
height: 100%;
border: 0;
}
#popupdarkbg {
position: fixed;
z-index: 5;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: hidden;
background-color: rgba(0, 0, 0, 0.75);
display: none;
}
I have a gallery. of images, I need to change the image when the user will press the arrow keys after the modal popup. left arrow key to change the image to the left and the right arrow key for right. I'm pretty new to JavaScript so I couldn't understand what function should I use to change the images to left and right.
I tried
.modal {
width: 58%;
height: 100%;
top: 0;
position: fixed;
display: none;
background-color: rgba(22, 22, 22, 0.5);
margin-left: 300px;
max-width: 779px;
min-width: 779px;
}
.modal-content {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}
.mySlides {
display: none;
}
.mySlides {
display: none;
}
.cursor {
cursor: pointer;
}
.cursor {
cursor: pointer;
}
.prev {
cursor: pointer;
position: relative;
top: -149px;
padding: 16px;
margin-top: -50px;
color: white;
font-weight: bold;
font-size: 20px;
border-radius: 0 3px 3px 0;
user-select: none;
-webkit-user-select: none;
left: -10%;
}
.next {
cursor: pointer;
position: relative;
top: -149px;
padding: 16px;
margin-top: -50px;
color: white;
font-weight: bold;
font-size: 20px;
border-radius: 0 3px 3px 0;
user-select: none;
-webkit-user-select: none;
left: 600px;
}
<div class="main-container">
<div class="row">
<div class="column">
<p align="center"><img src="https://source.unsplash.com/collection/190727/300x200" width="250" height="164" onclick="openModal();currentSlide(1)" class="hover-shadow cursor"></p>
</div>
<div class="column">
<p align="center"><img src="https://source.unsplash.com/collection/190727/300x210" width="250" height="164" onclick="openModal();currentSlide(2)" class="hover-shadow cursor"></p>
</div>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close cursor" onclick="closeModal()">×</span>
<div class="mySlides">
<img src="https://source.unsplash.com/collection/190727/300x200" style="width: 98%;
position: relative;
left: 10px;
top: 109px;">
</div>
<div class="mySlides">
<img src="https://source.unsplash.com/collection/190727/300x210" style="width: 98%;
position: relative;
left: 10px;
top: 109px;">
</div>
<a class="prev" id="prev1" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
document.addEventListener('keydown', function(e) {
if (e.keyCode === 37) {} else if (e.keyCode === 39) {}
});
You could create an array of all the images you wanted to cycle through.
Then create a count variable to index this array, using the remainder operator (%) to keep it within range.
This is what that would look like: (Use leftArrow and rightArrow to cycle)
const imageElement = document.getElementById('image');
const images = ['https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.PhOSiFj5bJt_uNbE7uw18QHaEK%26pid%3DApi&f=1', 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse4.mm.bing.net%2Fth%3Fid%3DOIP.qazsMQBX3pgWM7efm52WGwHaE7%26pid%3DApi&f=1', 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse3.mm.bing.net%2Fth%3Fid%3DOIP.M1ZwTSJXeW4021AafDtf9gHaE7%26pid%3DApi&f=1', 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.Wmr6TCnknZHO2DPszEf2bwHaE8%26pid%3DApi&f=1', 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.TRm_imdlOXbV4bggHxIcuwHaDt%26pid%3DApi&f=1', 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse3.mm.bing.net%2Fth%3Fid%3DOIP.0_abpwaxZ_xpc0V8kVZWMwHaLI%26pid%3DApi&f=1', 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse4.mm.bing.net%2Fth%3Fid%3DOIP.PPTPdfKia0RZBpC91MOG5wHaHa%26pid%3DApi&f=1'];
let current = 700;
document.addEventListener('keydown', function (e) {
if (e.code === "ArrowRight") current++
else if (e.code == "ArrowLeft") current--
imageElement.src = images[current % images.length];
e.preventDefault()
});
<img id="image" src="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.PhOSiFj5bJt_uNbE7uw18QHaEK%26pid%3DApi&f=1">
Note: KeyboardEvent.keyCode is deprecated. So I swapped it out for KeyboardEvent.code instead.
// Fix negative modulo
const mod = (n, m) => ((n % m) + m) % m;
let isModalOpen = true; // You need to toggle this on modal open.
// use a Modal Object singleton,
// or a Modal Class, whatever.
const images = [
"src 0",
"src 1",
"src 2",
]; // images by group of images.
const tot = images.length; // image length depend on how many images-by-group.
// You currently don't have any grouping.
// You need to implement that.
let idx = 0; // Depends on the clicked thumbnail index.
// might be: 1, 2, 0, - anything.
// It's on you to implement that!
// PS: The index can only depend on the index-by-images-group.
// And you're missing that galleries groups BTW.
// But that's also on you to figure out how to do it.
document.addEventListener("keydown", evt => {
const arrow = evt.key.match(/(?<=^Arrow)Right|Left/)?.[0];
// First make sure #modal is open, and it's an arrow key that's pressed.
if (!isModalOpen || !arrow) return; // Do nothing
// ALL OK! Slideshow time!
evt.preventDefault(); // prevent the browser default behavior (i.e: scrolling)
// Increment or decrement idx depending on the arrow key
idx += {Left: () => -1, Right: () => +1}[arrow]();
// Fix/Loop index
idx = mod(idx, tot);
// Get the image src to show!
const src = images[idx];
// Test:
console.log(src)
});
Click here and use arrow keys
I am experiencing issues when implementing two sets of code for two functions on a webpage I am designing. I am rather new to JS and JQuery, but none of the similar threads lead to a solution.
On my webpage I have a series of 100vh slideshows (code below) as well as one fullpage "welcome"screen above them. To transition between them, I am using a package that offers block scrolling.
Here is my code:
// Slideshow code, help from w3schools
var slideIndex = 1;
showDivs(slideIndex, show);
function plusDivs(n, show) {
showDivs(slideIndex += n, show);
}
function showDivs(n, show) {
var i;
var x = document.getElementsByClassName("mySlides"+show);
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "inline";
}
// blockScroller code from the docs on the linked package.
$(function() {
var blockScroller = $("#main-wrap").blockScroll();
});
I can, depending on which block of code is physically higher up in the script, get one of them to work at a time. However, when the block scrolling works, the slideshow breaks and none of that javascript has any effect on the page. This should tell you that for the sake of each individual scripts, all HTML and CSS requirements are met.
Any help to resolve this conflict would be great, and since this is my first question on stackoverflow if I butchered anything about location or related just tell me. If there is any more information I can provide I will gladly do so.
Here is a sampler of what I am talking about:
<!DOCTYPE html>
<html>
<head>
<!--style>
.slideshow{
z-index: 500;
position: relative;
height: 100vh;
width: 100%;
margin:auto;
overflow: hidden;
}
.slideshow > p{
position: absolute;
color: white;
background-color: black;
padding: 5px;
font-size: 24px;
margin: 0;
}
.mySlides1,.mySlides2{
width: 100%;
height: 100vh;
overflow: hidden;
object-fit: cover;
object-position: center center;
}
.slides_button{
position: absolute;
display: inline-block;
border: none;
padding:8px 16px;
cursor: pointer;
background-color: white;
}
.slides_button:hover{
background-color: black;
color: white;
}
.display_left{
position: absolute;
bottom: 50%;
left: 0%;
}
.display_right{
position: absolute;
bottom: 50%;
right: 0;
}
</style-->
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="SCRIPT HERE"></script> <script>
$(function () {
var blockScroller = $("#main-wrap").blockScroll();
$(function () {
function showDivs(n, show) {
var i;
var x = document.getElementsByClassName("mySlides"+show);
if (n > x.length) {slideIndex = 1};
if (n < 1) {slideIndex = x.length};
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
};
x[slideIndex-1].style.display = "block";
console.log(x[slideIndex-1])
};
var slideIndex = 1;
showDivs(2, 1);
showDivs(2, 2);
$(function () {
function plusDivs(n, show) {
showDivs(slideIndex += n, show);
};
})
});
});
</script>
<div id="main-wrap">
<div style="height:100vh;background-image:url(https://www.planwallpaper.com/static/images/518164-backgrounds.jpg)">
</div>
<div class="slideshow">
<p>slideshow 1</p>
<img class="mySlides1" src="https://cdn.pixabay.com/photo/2015/10/31/00/43/background-texture-1014963_960_720.jpg">
<button class="slides_button display_left" onclick="plusDivs(-1,1)">❮</button>
<button class="slides_button display_right" onclick="plusDivs(1,1)">❯</button>
<img class="mySlides1" src="https://image.freepik.com/free-vector/orange-geometric-background-with-halftone-dots_1035-7243.jpg">
<img class="mySlides1" src="https://cdn.pixabay.com/photo/2015/10/31/00/43/background-texture-1014963_960_720.jpg">
<img class="mySlides1" src="https://image.freepik.com/free-vector/orange-geometric-background-with-halftone-dots_1035-7243.jpg">
</div>
<div class="slideshow">
<p>slideshow 2</p>
<img class="mySlides2" src="https://image.freepik.com/free-psd/abstract-background-design_1297-87.jpg">
<button class="slides_button display_left" onclick="plusDivs(-1,2)">❮</button>
<button class="slides_button display_right" onclick="plusDivs(1,2)">❯</button>
<img class="mySlides2" src="http://images.all-free-download.com/images/graphiclarge/flower_pink_background_vector_art_148632.jpg">
<img class="mySlides2" src="http://images.all-free-download.com/images/graphiclarge/clouds_in_sky_background_192377.jpg">
</div>
</div>
</body>
</html>
blockerScoll js script
not work because show in showDivs(slideIndex, show); is undefined, it should be like this
showDivs(slideIndex, 1);
showDivs(slideIndex, 2);
demo
//This is only for the block scrolling. If you move this
//ABOVE the previous section, then it will take over.
$(function() {
var blockScroller = $("#main-wrap").blockScroll();
});
//This is the slideshow section. Move this above the block scroll
//and this works.
function showDivs(n, show) {
var i;
var x = document.getElementsByClassName("mySlides" + show);
if(n > x.length) {
slideIndex = 1
}
if(n < 1) {
slideIndex = x.length
}
for(i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex - 1].style.display = "inline";
//console.log(x[slideIndex - 1])
}
var slideIndex = 1;
showDivs(slideIndex, 1);
showDivs(slideIndex, 2);
function plusDivs(n, show) {
showDivs(slideIndex += n, show);
}
.slideshow {
z-index: 500;
position: relative;
height: 100vh;
width: 100%;
margin: auto;
overflow: hidden;
}
.slideshow>p {
position: absolute;
color: white;
background-color: black;
padding: 5px;
font-size: 24px;
margin: 0;
}
.mySlides1,
.mySlides2 {
width: 100%;
height: 100vh;
overflow: hidden;
object-fit: cover;
object-position: center center;
}
.slides_button {
position: absolute;
display: inline-block;
border: none;
padding: 8px 16px;
cursor: pointer;
background-color: white;
}
.slides_button:hover {
background-color: black;
color: white;
}
.display_left {
position: absolute;
bottom: 50%;
left: 0%;
}
.display_right {
position: absolute;
bottom: 50%;
right: 0;
}
<link rel="stylesheet" type="text/css" href="//www.dominikgorecki.com/p/block-scroll/blockScroll.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//www.dominikgorecki.com/p/block-scroll/js/blockScroll.js"></script>
<div id="main-wrap">
<div style="height:100vh;background-image:url(https://www.planwallpaper.com/static/images/518164-backgrounds.jpg)">
</div>
<div class="slideshow">
<p>slideshow 1</p>
<img class="mySlides1" src="https://cdn.pixabay.com/photo/2015/10/31/00/43/background-texture-1014963_960_720.jpg">
<button class="slides_button display_left" onclick="plusDivs(-1,1)">❮</button>
<button class="slides_button display_right" onclick="plusDivs(1,1)">❯</button>
<img class="mySlides1" src="https://image.freepik.com/free-vector/orange-geometric-background-with-halftone-dots_1035-7243.jpg">
<img class="mySlides1" src="https://cdn.pixabay.com/photo/2015/10/31/00/43/background-texture-1014963_960_720.jpg">
<img class="mySlides1" src="https://image.freepik.com/free-vector/orange-geometric-background-with-halftone-dots_1035-7243.jpg">
</div>
<div class="slideshow">
<p>slideshow 2</p>
<img class="mySlides2" src="https://image.freepik.com/free-psd/abstract-background-design_1297-87.jpg">
<button class="slides_button display_left" onclick="plusDivs(-1,2)">❮</button>
<button class="slides_button display_right" onclick="plusDivs(1,2)">❯</button>
<img class="mySlides2" src="http://images.all-free-download.com/images/graphiclarge/flower_pink_background_vector_art_148632.jpg">
<img class="mySlides2" src="http://images.all-free-download.com/images/graphiclarge/clouds_in_sky_background_192377.jpg">
</div>
</div>
I am learning javascript these days and I have a little problem with my code.
I have three elements on page wrapper1, wrapper2 and wrapper3 and every of these has its triggerand redbox element.
My goal is when the trigger is hit, it will show the redbox element corresponding to number.
Examples:
clicking trigger1 inside wrapper1 element shows up redbox1 element,
trigger2 inside wrapper2 element shows up redbox2 element etc.
The problem is, when I click on trigger3 for example it always shows redbox1 element. (as example shows).
What I am doing wrong? I am just a begginer.
function showTheRedBox() {
var theRedBox = document.getElementsByClassName('redbox');
theRedBox[0].style.display = 'block';
}
body {background: #222;}
.wrapper {
background: yellow;
width: 100px;
height: 100px;
}
.trigger {
background: blue;
width: 50px;
height: 50px;
position: absolute;
margin-top: 50px;
margin-left: 50px;
}
.redbox {
background: red;
width: 200px;
height: 100px;
margin-left: 100px;
position: absolute;
display: none;
}
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox();">trigger1</div>
<div class="redbox">hurrah1</div>
wrapper1</div>
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox();">trigger2</div>
<div class="redbox">hurrah2</div>
wrapper2</div>
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox();">trigger3</div>
<div class="redbox">hurrah3</div>
wrapper3</div>
You can use a for loop and a closure to access the .wrapper information for each onclick event. This method will work whether there are the same amount of children or not, and will always show the correct child.
Also, it is best to not use inline JavaScript attributes (e.g. onclick="showTheRedBox();") you should always assign your event handlers in your script for readability and maintainability.
var wrappers = document.querySelectorAll('.wrapper'), i;
var redboxes = document.querySelectorAll('.redbox');
for(i = wrappers.length - 1; i >= 0; --i) {
(function(wrapper){
wrapper.querySelector('.trigger').onclick = function() {
hideAll();
wrapper.querySelector('.redbox').style.display = 'block';
}
})(wrappers[i]);
}
function hideAll() {
for(i = redboxes.length - 1; i >= 0; --i) {
redboxes[i].style.display = 'none';
}
}
var wrappers = document.querySelectorAll('.wrapper'), i;
var redboxes = document.querySelectorAll('.redbox');
for(i = wrappers.length - 1; i >= 0; --i) {
(function(wrapper){
wrapper.querySelector('.trigger').onclick = function() {
hideAll();
wrapper.querySelector('.redbox').style.display = 'block';
}
})(wrappers[i]);
}
function hideAll() {
for(i = redboxes.length - 1; i >= 0; --i) {
redboxes[i].style.display = 'none';
}
}
body {background: #222;}
.wrapper {
background: yellow;
width: 100px;
height: 100px;
}
.trigger {
background: blue;
width: 50px;
height: 50px;
position: absolute;
margin-top: 50px;
margin-left: 50px;
}
.redbox {
background: red;
width: 200px;
height: 100px;
margin-left: 100px;
position: absolute;
display: none;
}
<div class="wrapper">
<div class="trigger">trigger1</div>
<div class="redbox">hurrah1</div>
wrapper1</div>
<div class="wrapper">
<div class="trigger">trigger2</div>
<div class="redbox">hurrah2</div>
wrapper2</div>
<div class="wrapper">
<div class="trigger">trigger3</div>
<div class="redbox">hurrah3</div>
wrapper3</div>
This method will also work, but it will use more memory as it queries the DOM once more than the above solution.
var wrappers = document.querySelectorAll('.wrapper'), i;
var redboxes = document.querySelectorAll('.redbox');
for(i = wrappers.length - 1; i >= 0; --i) {
wrappers[i].querySelector('.trigger').onclick = function() {
hideAll();
this.parentNode.querySelector('.redbox').style.display = 'block';
}
}
function hideAll() {
for(i = redboxes.length - 1; i >= 0; --i) {
redboxes[i].style.display = 'none';
}
}
var wrappers = document.querySelectorAll('.wrapper'), i;
var redboxes = document.querySelectorAll('.redbox');
for(i = wrappers.length - 1; i >= 0; --i) {
wrappers[i].querySelector('.trigger').onclick = function() {
hideAll();
this.parentNode.querySelector('.redbox').style.display = 'block';
}
}
function hideAll() {
for(i = redboxes.length - 1; i >= 0; --i) {
redboxes[i].style.display = 'none';
}
}
body {background: #222;}
.wrapper {
background: yellow;
width: 100px;
height: 100px;
}
.trigger {
background: blue;
width: 50px;
height: 50px;
position: absolute;
margin-top: 50px;
margin-left: 50px;
}
.redbox {
background: red;
width: 200px;
height: 100px;
margin-left: 100px;
position: absolute;
display: none;
}
<div class="wrapper">
<div class="trigger">trigger1</div>
<div class="redbox">hurrah1</div>
wrapper1</div>
<div class="wrapper">
<div class="trigger">trigger2</div>
<div class="redbox">hurrah2</div>
wrapper2</div>
<div class="wrapper">
<div class="trigger">trigger3</div>
<div class="redbox">hurrah3</div>
wrapper3</div>
The problem you have was that the method "getElementsByClassName", returns you an Array that contains all the elements of that class. So, when you where doing this:
theRedBox[0].style.display = 'block'
You were changing the display style of the First element of the Array, in this case "wrapper1".
Here's a modify version that functions whit the others wrappers:
<!DOCTYPE html>
<html lang = 'es'>
<head>
<title> MY TEST </title>
<style>
body {
background: #222;
}
.wrapper {
background: yellow;
width: 100px;
height: 100px;
}
.trigger {
background: blue;
width: 50px;
height: 50px;
position: absolute;
margin-top: 50px;
margin-left: 50px;
}
.redbox {
background: red;
width: 200px;
height: 100px;
margin-left: 100px;
position: absolute;
display: none;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox(0)">trigger1</div> <!-- When the onClick event is trigered the function "showTheRedBox receives a parameter , that parameter is the position of the element in the Array "theRedBox"-->
<div class="redbox">hurrah1</div>
wrapper1
</div>
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox(1)">trigger2</div>
<div class="redbox">hurrah2</div>
wrapper2
</div>
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox(2)">trigger3</div>
<div class="redbox">hurrah3</div>
wrapper3</div>
<script>
function showTheRedBox(wrapperNumber) {
var theRedBox = document.getElementsByClassName('redbox');
theRedBox[wrapperNumber].style.display = 'block';
}
</script>
</body>
</html>
In one of my projects, I have requirement of multiple pop up div's on the same page. That means when user clicks on a link, some content should open in a pop up. There will be many such links with their own pop ups. With little knowledge of javascript, I have tried to write a javascript for it but it works only for one pop up. When I click on second, third... links, only first pop up opens rather than opening second, third... pop ups. Here is my code. Please tell the modifications to it.
<!DOCTYPE html>
<html >
<head>
<script>
window.document.onkeydown = function (e)
{
if (!e)
{
e = event;
}
if (e.keyCode == 27)
{
lightbox_close();
}
}
function lightbox_open()
{
window.scrollTo(0,0);
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
}
function lightbox_close()
{
document.getElementById('light').style.display='none';
document.getElementById('fade').style.display='none';
}
</script>
<style>
#fade
{
display: none;
position: fixed;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: #000;
z-index:1001;
-moz-opacity: 0.7;
opacity:.70;
filter: alpha(opacity=70);
}
#light
{
display: none;
position: absolute;
top: 50%;
left: 50%;
width: 300px;
height: 200px;
margin-left: -150px;
margin-top: -100px;
padding: 10px;
border: 2px solid #FFF;
background: #CCC;
z-index:1002;
overflow:visible;
}
</style>
</head>
<body>
Open 1
<div id="light">div 1</div>
<div id="fade" onClick="lightbox_close();"></div>
Open 2
<div id="light">div 2</div>
<div id="fade" onClick="lightbox_close();"></div>
Open 3
<div id="light">div 3</div>
<div id="fade" onClick="lightbox_close();"></div>
</body>
</html>
Here's a way to achieve what you want. I'm sure it can be improved, but it's up to you then.
First, IDs should be unique across the page. If you want to group elements, give them a shared class instead.
With the changes, your HTML would look like this:
Open 1
<div class="light">div 1</div>
<div class="fade" onClick="lightbox_close()"></div>
Open 2
<div class="light">div 2</div>
<div class="fade" onClick="lightbox_close()"></div>
Open 3
<div class="light">div 3</div>
<div class="fade" onClick="lightbox_close()"></div>
Your CSS:
html, body {
width: 100%;
height: 100%;
}
.fade {
display: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
z-index:1001;
-moz-opacity: 0.7;
opacity:.70;
filter: alpha(opacity=70);
}
.light {
display: none;
position: absolute;
top: 50%;
left: 50%;
width: 300px;
height: 200px;
margin-left: -150px;
margin-top: -100px;
padding: 10px;
border: 2px solid #FFF;
background: #CCC;
z-index:1002;
overflow:visible;
}
And your Javascript:
window.document.onkeydown = function (e) {
if (!e) {
e = event;
}
if (e.keyCode == 27) {
lightbox_close();
}
}
// Note that the function is receiving the clicked element reference.
function lightbox_open(el) {
window.scrollTo(0,0);
// All the anchors that have a class lightbox.
var anchors = document.querySelectorAll('a.lightbox');
// All the elements with class light.
var light = document.querySelectorAll('.light');
// All the elements with class fade.
var fade = document.querySelectorAll('.fade');
// Iterate over the anchors elements.
for (var i = 0; i < anchors.length; i++) {
// If the anchor matches the clicked one.
if (anchors[i] == el) {
// Look for the light and fade with the same index
// and display them.
light[i].style.display = 'block';
fade[i].style.display = 'block';
}
}
}
function lightbox_close() {
// All the elements with class light or fade.
var els = document.querySelectorAll('.light, .fade');
// Loop through the list.
for (var i = 0; i < els.length; i++) {
// Hide them.
els[i].style.display = 'none';
}
}
Demo