Using Intersection Observer for lazyloading on cloned elements - javascript

I have a modified Bootstrap 4 carousel that has multiple items and scrolls one-by-one using this JavaScript:
$('.carousel[data-type="multi"] .carousel-item').each(function() {
var next = $(this).next();
if (!next.length) {
next = $(this).siblings(':first');
}
next.children(':first-child').clone().appendTo($(this));
for (var i = 0; i < 2; i++) {
next = next.next();
if (!next.length) {
next = $(this).siblings(':first');
}
next.children(':first-child').clone().appendTo($(this));
}
});
This creates a clone of each carousel-item with multiple carousel-columns, like this:
<div class="carousel-item active">
<div class="carousel-col">
<img src="" class="lazy" /> <!-- This image loads -->
</div>
<div class="carousel-col">
<img src="" class="lazy" />
</div>
<div class="carousel-col">
<img src="" class="lazy" />
</div>
<div class="carousel-col">
<img src="" class="lazy" />
</div>
</div>
<div class="carousel-item">
<div class="carousel-col">
<img src="" class="lazy" /> <!-- This image loads -->
</div>
<div class="carousel-col">
<img src="" class="lazy" />
</div>
<div class="carousel-col">
<img src="" class="lazy" />
</div>
<div class="carousel-col">
<img src="" class="lazy" />
</div>
</div>
I'm trying to implement lazy-loading with the Intersection Observer API, however inside the carousel it only works on the image in the first carousel-col in each carousel-item. I'm guessing this is due to the cloning but I'm not sure how to remedy the conflict. The API doesn't see to recognize that the cloned images exist.
Does anyone have any insight as to how I might go about fixing this?
Here's the JavaScript I'm using for lazyloading:
document.addEventListener("DOMContentLoaded", function() {
var lazyloadImages;
if ("IntersectionObserver" in window) {
lazyloadImages = document.querySelectorAll(".lazy");
var imageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
var image = entry.target;
image.src = image.dataset.src;
image.classList.remove("lazy");
imageObserver.unobserve(image);
}
});
});
lazyloadImages.forEach(function(image) {
imageObserver.observe(image);
});
} else {
var lazyloadThrottleTimeout;
lazyloadImages = document.querySelectorAll(".lazy");
function lazyload () {
if(lazyloadThrottleTimeout) {
clearTimeout(lazyloadThrottleTimeout);
}
lazyloadThrottleTimeout = setTimeout(function() {
var scrollTop = window.pageYOffset;
lazyloadImages.forEach(function(img) {
if(img.offsetTop < (window.innerHeight + scrollTop)) {
img.src = img.dataset.src;
img.classList.remove('lazy');
}
});
if(lazyloadImages.length == 0) {
document.removeEventListener("scroll", lazyload);
window.removeEventListener("resize", lazyload);
window.removeEventListener("orientationChange", lazyload);
}
}, 20);
}
document.addEventListener("scroll", lazyload);
window.addEventListener("resize", lazyload);
window.addEventListener("orientationChange", lazyload);
}
});

Related

Div isn't displayed after JavaScript element is created

I'm trying to make a div labeled called .overlay-text to be shown when a video is clicked but it isn't showing up according to its content.
const elementsClicked = document.querySelectorAll(".thumbnail, .overlay-text");
const currentThumb = document.querySelector('.container-projects');
elementsClicked.forEach(element => {
element.addEventListener("click", function() {
const parent = this.closest(".item-project");
const thumbnailCurrent = parent.querySelector(".thumbnail-current");
const video = parent.querySelector(".vid");
if (this.classList.contains("thumbnail)) {
if (this.tagName === "VIDEO") {
thumbnailCurrent.innerHTML = "";
const videoCloned = document.createElement("video");
videoCloned.setAttribute("controls", "");
videoCloned.setAttribute("src", this.getAttribute("src"));
videoCloned.setAttribute("type", this.getAttribute("type"));
videoCloned.classList.add("vid-current");
thumbnailCurrent.appendChild(videoCloned);
videoCloned.addEventListener('play', event => {
const videos = currentThumb.querySelectorAll('video');
videos.forEach(v => {
if (v !== event.target) {
v.pause();
}
});
});
videoCloned.addEventListener('pause', event => {
this.parentNode.querySelector(".overlay-text").classList.remove("hidden");
});
videoCloned.play()
} else {
thumbnailCurrent.innerHTML = this.outerHTML;
}
}
else {
video.classList.toggle("hidden");
this.classList.toggle("hidden");
if (video.paused) {
video.play();
} else {
video.pause();
}
}
});
});
const videos = currentThumb.querySelectorAll('video');
videos.forEach(video => {
video.addEventListener("play", function() {
this.parentNode.querySelector(".overlay-text").classList.add("hidden");
});
video.addEventListener("pause", function() {
this.parentNode.querySelector(".overlay-text").classList.remove("hidden");
});
video.addEventListener('play', event => {
videos.forEach(v => {
if (v !== event.target) {
v.pause();
}
});
});
});
This function above makes a gallery works, showing the video or image up when is clicked inside a div labeled .thumbnail-current. It also let the video play if is clicked in its overlay-text and toggle between hidden or not if it is playing or paused.
Here's the HTML code:
<div class="thumbnail-current">
<video src="video.mp4" type="video/mp4" class="vid" id="video1" controls></video>
<div class="overlay-text" id="text1">
<h4>One title</h4>
<p>One description.</p>
</div>
</div>
<div class="container-thumbnail">
<p>&lt</p>
<video src="video.mp4" type="video/mp4" class="thumbnail vid-mini" id="mini1"></video>
<img src="images/image (2).jpg" class="thumbnail" id="mini2" alt="">
<img src="images/image (3).jpg" class="thumbnail" id="mini3" alt="">
<img src="images/image (4).jpg" class="thumbnail" id="mini4" alt="">
<img src="images/image (5).jpg" class="thumbnail" id="mini5" alt="">
<img src="images/image (6).jpg" class="thumbnail" id="mini6" alt="">
<p>&gt</p>
</div>
</div>
<div class="item-project text">
<div class="thumbnail-current">
<video src="video2.mp4" class="vid" id="video2" controls></video>
<div class="overlay-text" id="text2">
<h4>Another title</h4>
<p>Another title.</p>
</div>
</div>
<div class="container-thumbnail">
<p>&lt</p>
<video src="video2.mp4" class="thumbnail vid-mini" id="mini1"></video>
<img src="images/image (2).jpg" class="thumbnail" id="mini2" alt="">
<img src="images/image (3).jpg" class="thumbnail" id="mini3" alt="">
<img src="images/image (4).jpg" class="thumbnail" id="mini4" alt="">
<img src="images/image (5).jpg" class="thumbnail" id="mini5" alt="">
<img src="images/image (6).jpg" class="thumbnail" id="mini6" alt="">
<p>&gt</p>
</div>
</div>
I have tried several lines of codes, but it isn't working.
I want .overlay-text to be shown when videoCloned is created in the .miniatura-current div.
Thanks.

Toggle between multiple images

I have 4 images black, red, orange and green - and the disabled version in gray.
What I want to achieve is that when I click on a disabled one, the other ones should turn gray/disabled and the one clicked should turn to his color image.
I tried following now this will get his child div and will do the toggle trick with the clicked image, but it won't disable the other ones. How can I disable all the other ones?
$('.toggle').each(function() {
var clickCounter = 0,
firstEdit = false;
$(this).on('click', function() {
clickCounter++;
if (clickCounter == 1 || firstEdit == true) {
$(this).toggle();
$(this).next('.toggled').toggle();
clickCounter = 0;
firstEdit = true;
}
});
});
$('.toggled').on('click', function() {
$(this).toggle();
$(this).prev('.toggle').toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div class="toggle"><img class="" src="data/img/controller/orange.jpg"></div>
<div class="toggled"><img class="" src="data/img/controller/orange_disabled.jpg"></div>
<div class="toggle"><img class="" src="data/img/controller/red.jpg"></div>
<div class="toggled"><img class="" src="data/img/controller/red_disabled.jpg"></div>
<div class="toggle"><img class="" src="data/img/controller/black.jpg"></div>
<div class="toggled"><img class="" src="data/img/controller/black_disabled.jpg"></div>
<div class="toggle"><img class="" src="data/img/controller/green.jpg"></div>
<div class="toggled"><img class="" src="data/img/controller/green_disabled.jpg"></div>
You'll need loop through all images in onclick event handler and set proper class on each image. Also note, you could make images look grey with simple css filter, don't need create separate images
const test = document.getElementById("test");
test.addEventListener("click", e =>
{
for(let i = 0, children = test.children; i < children.length; i++)
{
children[i].classList.toggle("selected", children[i] === e.target);
}
});
.content > img:not(.selected)
{
filter: saturate(0);
opacity: 0.5;
}
<span id="test" class="content">
<img src="https://lh3.googleusercontent.com/IlhDxQVsR17dwwER5xYZJej867KrdSx0K5eyRP2RFP4eQJMD2pi0ZGBhrMOcajBUP9M54lpmIr90JecPUFGPaRe3sDZ82RvHBSw1rw-YJvQs7J8K3g=w102-h68-n-l50-sg-rj">
<img src="https://lh3.googleusercontent.com/taykG37GWDgY-FGkdogDvsHSJMUGRMvkuVRT6yR-5UNkKvGRKeRlpGYXlslocOcS0txlfUdGW59JGtzADknxbMqnh6AtVCv9EXyB8nHp80YsRNA0Yw=w102-h68-n-l50-sg-rj">
<img src="https://lh3.googleusercontent.com/aS2Up3osDMLTua1vXPTqnXko13KbIAmB0nQ44AP_IFTEt-VjUa6Tz2MC9jdH11bsZfjdiR8z4HbnxvhmmxSU1swKrtjc5PXreP6i=w102-h68-n-l50-sg-rj">
<img src="https://lh3.googleusercontent.com/dTH5_J82_TqXaLW_Hzq1rbMVqfzRWG9PkcKgHdjXphAy9M4MZF5Q7_cQZeM1kbqEYMysrBLlY4szACDZwIbP7Jm17BnGNjT0Tht8Qw=w102-h68-n-l50-sg-rj">
</span>
P.S.
Please don't use bloatware jquery, save the planet.
Delegation for dynamic content
jQuery version
Change toggleClass to addClass to not toggle the clicked image
$('#container').on('click', 'img', function() {
$(this).siblings().each(function() { $(this).removeClass('selected') });
$(this).toggleClass('selected')
});
.content>img:not(.selected) {
filter: saturate(0);
opacity: 0.5;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div class="content">
<img src="https://lh3.googleusercontent.com/IlhDxQVsR17dwwER5xYZJej867KrdSx0K5eyRP2RFP4eQJMD2pi0ZGBhrMOcajBUP9M54lpmIr90JecPUFGPaRe3sDZ82RvHBSw1rw-YJvQs7J8K3g=w102-h68-n-l50-sg-rj">
<img src="https://lh3.googleusercontent.com/taykG37GWDgY-FGkdogDvsHSJMUGRMvkuVRT6yR-5UNkKvGRKeRlpGYXlslocOcS0txlfUdGW59JGtzADknxbMqnh6AtVCv9EXyB8nHp80YsRNA0Yw=w102-h68-n-l50-sg-rj">
<img src="https://lh3.googleusercontent.com/aS2Up3osDMLTua1vXPTqnXko13KbIAmB0nQ44AP_IFTEt-VjUa6Tz2MC9jdH11bsZfjdiR8z4HbnxvhmmxSU1swKrtjc5PXreP6i=w102-h68-n-l50-sg-rj">
<img src="https://lh3.googleusercontent.com/dTH5_J82_TqXaLW_Hzq1rbMVqfzRWG9PkcKgHdjXphAy9M4MZF5Q7_cQZeM1kbqEYMysrBLlY4szACDZwIbP7Jm17BnGNjT0Tht8Qw=w102-h68-n-l50-sg-rj">
</div>
<div class="content">
<img src="https://lh3.googleusercontent.com/IlhDxQVsR17dwwER5xYZJej867KrdSx0K5eyRP2RFP4eQJMD2pi0ZGBhrMOcajBUP9M54lpmIr90JecPUFGPaRe3sDZ82RvHBSw1rw-YJvQs7J8K3g=w102-h68-n-l50-sg-rj">
<img src="https://lh3.googleusercontent.com/taykG37GWDgY-FGkdogDvsHSJMUGRMvkuVRT6yR-5UNkKvGRKeRlpGYXlslocOcS0txlfUdGW59JGtzADknxbMqnh6AtVCv9EXyB8nHp80YsRNA0Yw=w102-h68-n-l50-sg-rj">
<img src="https://lh3.googleusercontent.com/aS2Up3osDMLTua1vXPTqnXko13KbIAmB0nQ44AP_IFTEt-VjUa6Tz2MC9jdH11bsZfjdiR8z4HbnxvhmmxSU1swKrtjc5PXreP6i=w102-h68-n-l50-sg-rj">
<img src="https://lh3.googleusercontent.com/dTH5_J82_TqXaLW_Hzq1rbMVqfzRWG9PkcKgHdjXphAy9M4MZF5Q7_cQZeM1kbqEYMysrBLlY4szACDZwIbP7Jm17BnGNjT0Tht8Qw=w102-h68-n-l50-sg-rj">
</div>
</div>
Vanilla - it does not toggle the clicked image
const container = document.getElementById('container');
container.addEventListener('click', e => {
const tgt = e.target;
if (!tgt.matches('img')) return;
const images = tgt.closest('.content').querySelectorAll('img');
images.forEach(img => img.classList.toggle('selected', img === tgt));
});
.content>img:not(.selected) {
filter: saturate(0);
opacity: 0.5;
}
<div id="container">
<div class="content">
<img src="https://lh3.googleusercontent.com/IlhDxQVsR17dwwER5xYZJej867KrdSx0K5eyRP2RFP4eQJMD2pi0ZGBhrMOcajBUP9M54lpmIr90JecPUFGPaRe3sDZ82RvHBSw1rw-YJvQs7J8K3g=w102-h68-n-l50-sg-rj">
<img src="https://lh3.googleusercontent.com/taykG37GWDgY-FGkdogDvsHSJMUGRMvkuVRT6yR-5UNkKvGRKeRlpGYXlslocOcS0txlfUdGW59JGtzADknxbMqnh6AtVCv9EXyB8nHp80YsRNA0Yw=w102-h68-n-l50-sg-rj">
<img src="https://lh3.googleusercontent.com/aS2Up3osDMLTua1vXPTqnXko13KbIAmB0nQ44AP_IFTEt-VjUa6Tz2MC9jdH11bsZfjdiR8z4HbnxvhmmxSU1swKrtjc5PXreP6i=w102-h68-n-l50-sg-rj">
<img src="https://lh3.googleusercontent.com/dTH5_J82_TqXaLW_Hzq1rbMVqfzRWG9PkcKgHdjXphAy9M4MZF5Q7_cQZeM1kbqEYMysrBLlY4szACDZwIbP7Jm17BnGNjT0Tht8Qw=w102-h68-n-l50-sg-rj">
</div>
<div class="content">
<img src="https://lh3.googleusercontent.com/IlhDxQVsR17dwwER5xYZJej867KrdSx0K5eyRP2RFP4eQJMD2pi0ZGBhrMOcajBUP9M54lpmIr90JecPUFGPaRe3sDZ82RvHBSw1rw-YJvQs7J8K3g=w102-h68-n-l50-sg-rj">
<img src="https://lh3.googleusercontent.com/taykG37GWDgY-FGkdogDvsHSJMUGRMvkuVRT6yR-5UNkKvGRKeRlpGYXlslocOcS0txlfUdGW59JGtzADknxbMqnh6AtVCv9EXyB8nHp80YsRNA0Yw=w102-h68-n-l50-sg-rj">
<img src="https://lh3.googleusercontent.com/aS2Up3osDMLTua1vXPTqnXko13KbIAmB0nQ44AP_IFTEt-VjUa6Tz2MC9jdH11bsZfjdiR8z4HbnxvhmmxSU1swKrtjc5PXreP6i=w102-h68-n-l50-sg-rj">
<img src="https://lh3.googleusercontent.com/dTH5_J82_TqXaLW_Hzq1rbMVqfzRWG9PkcKgHdjXphAy9M4MZF5Q7_cQZeM1kbqEYMysrBLlY4szACDZwIbP7Jm17BnGNjT0Tht8Qw=w102-h68-n-l50-sg-rj">
</div>
</div>

Javascript function not reachable after settimeout

I have designed following code snippet:
<div id="content">
<h3>Select Images Below</h3>
<ul id="imagegallery">
<li>
<a class='a' href="./img/team/t1.jpg" title="The crowd goes wild" onclick="">
<img src="./img/team/t1.jpg" height="50px" width="50px" alt="the band in concert" />
</a>
</li>
<li>
<a class='a' href="./img/team/t2.jpg" title="An atmospheric moment">
<img src="./img/team/t2.jpg" height="50px" width="50px" alt="the bassist" />
</a>
</li>
<li>
<a class='a' href="./img/team/t3.jpg" title="Rocking out">
<img id='image' src="./img/team/t3.jpg" height="50px" width="50px" alt="the guitarist" />
</a>
</li>
<li>
<a class='a'href="./img/team/t4.jpg" title="Encore! Encore!">
<img id='image' src="./img/team/t4.jpg" height="50px" width="50px" alt="the audience" />
</a>
</li>
</ul>
<div>
<img id='placeholder', src="./img/resources/neutral_1.jpg", height="450px" width="550px" alt="Image gooes here", style="margin-bottom: 50px;padding: 10px;">
</div>
<div id="loading">
<img src="img/loading.gif" alt="">
</div>
<div id="show">
<h1 id ='h'>It works</h1>
</div>
</div>
and the JS for this code is something like this
window.onload = function() {
var links = document.getElementsByClassName('a');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('click', function(e) {
// Hide results
document.getElementById('placeholder').style.display = 'none';
// Show loader
document.getElementById('loading').style.display = 'block';
setTimeout(showpic(this), 2000);
e.preventDefault();
});
}
function showPic(whichpic) {
document.getElementById('placeholder').style.display = 'block';
var source = whichpic.getAttribute('href');
var placeholder = document.getElementById('placeholder');
placeholder.setAttribute('src', source);
return false;
}
};
I am trying to show the clicked image in the placeholder below,reading the source from href of a tags and assigning it to src of placeholder, but the problem I am facing is that showpic is never called/reached. how should i modify my code to resolve this problem. I click the image, loader appears and then image loads in browser window
This is not correct
setTimeout(showpic(this), 2000);
You should pass a function to setTimeout but you are calling it and actually passing some result of one's execution. You should do like this, for example
setTimeout(() => showpic(this), 2000);
You have a typo. You declare your function as showPic but call it as showpic
Correct showpic(this) to () => showpic(this).Your call to the showPic function is misspelled. Also your showPicfunction does not need to be wrapped inside of your window.onload function. Your JS should look like this and it should work:
window.onload = function() {
var links = document.getElementsByClassName('a');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('click', function(e) {
// Hide results
document.getElementById('placeholder').style.display = 'none';
// Show loader
document.getElementById('loading').style.display = 'block';
setTimeout(() => showPic(this), 2000);
e.preventDefault();
});
}
}
function showPic(whichpic) {
document.getElementById('placeholder').style.display = 'block';
var source = whichpic.getAttribute('href');
var placeholder = document.getElementById('placeholder');
placeholder.setAttribute('src', source);
return false;
}

Automatic Cycling Carousel for several divs and different img

I am trying to write a function, that will automatically carousel cycle through img thumbs on my site with 12 different sets of images, which are just put together in one div. The javascript below works, but only as long, as I have the same amount of images in every div. I am also sure, that I took the long route of telling javascript, what to do in terms of variables so my question is, what should I change, so that I can have different amounts of img in my separate divs?
Thanks a lot for any tips!
var myIndex = 0;
carousel();
function carousel() {
var i;
var u = document.getElementsByClassName("thumbs1");
var v = document.getElementsByClassName("thumbs2");
var w = document.getElementsByClassName("thumbs3");
// and so on ...
for (i = 0; i < w.length; i++) {
u[i].style.display = "none";
v[i].style.display = "none";
w[i].style.display = "none";
// ...
}
myIndex++;
if (myIndex > w.length) {myIndex = 1}
u[myIndex-1].style.display = "inline-block";
v[myIndex-1].style.display = "inline-block";
w[myIndex-1].style.display = "inline-block";
// ...
setTimeout(carousel, 1200); // Change image every 2 seconds
}
<div class="imageholder">
<img class="thumbs1" src="image11.jpg">
<img class="thumbs1" src="image12.jpg">
<img class="thumbs1" src="image13.jpg">
<img class="thumbs1" src="image14.jpg">
</div>
<div class="imageholder">
<img class="thumbs2" src="image21.jpg">
<img class="thumbs2" src="image22.jpg">
<img class="thumbs2" src="image23.jpg">
</div>
<div class="imageholder">
<img class="thumbs3" src="image31.jpg">
<img class="thumbs3" src="image32.jpg">
<img class="thumbs3" src="image33.jpg">
<img class="thumbs3" src="image34.jpg">
<img class="thumbs3" src="image35.jpg">
</div>
<!-- ... -->
Keep counting the myIndex (so do not reset it) and use the modulus % operator with the array length of each image set.
Further notes:
The value of Timeout/Interval is in milliseconds. So 2000ms = 2s
You do not need to get all elements' references again with each call to carousel(). Just do it once at the beginning.
If something is not clear, please ask.
var myIndex = 0;
var i;
var u = document.getElementsByClassName("thumbs1");
var v = document.getElementsByClassName("thumbs2");
var w = document.getElementsByClassName("thumbs3");
var allThumbs = [u, v, w];
var myInterval = setInterval(carousel, 2000); // Change image every 2 seconds
function carousel() {
myIndex++;
for (i = 0; i < allThumbs.length; i++) {
allThumbs[i][(myIndex - 1) % allThumbs[i].length].style.display = "none";
allThumbs[i][myIndex % allThumbs[i].length].style.display = "inline-block";
}
}
.thumbs1:not(:first-child),
.thumbs2:not(:first-child),
.thumbs3:not(:first-child) {
display: none;
}
<div class="imageholder">
<img class="thumbs1" src="image11.jpg" alt="1">
<img class="thumbs1" src="image12.jpg" alt="2">
<img class="thumbs1" src="image13.jpg" alt="3">
<img class="thumbs1" src="image14.jpg" alt="4">
</div>
<div class="imageholder">
<img class="thumbs2" src="image21.jpg" alt="1">
<img class="thumbs2" src="image22.jpg" alt="2">
<img class="thumbs2" src="image23.jpg" alt="3">
</div>
<div class="imageholder">
<img class="thumbs3" src="image31.jpg" alt="1">
<img class="thumbs3" src="image32.jpg" alt="2">
<img class="thumbs3" src="image33.jpg" alt="3">
<img class="thumbs3" src="image34.jpg" alt="4">
<img class="thumbs3" src="image35.jpg" alt="5">
</div>

Changing all images on timer with JS

I have this 3x3 img gallery. I need all of them to change every certain time with JS.
So far I managed to do this to one of the images. I don't know how to target them all.
<script>
var images = ["http://lorempixel.com/250/200/", "http://lorempixel.com/250/150/"];
var i = 0;
var renew = setInterval(function(){
if(images.length == i){
i = 0;
}
else {
document.getElementByClassName('galleryItem').src = images[i];
i++;
}
},1000);
</script>
<div class="galleryWrapper">
<div class="galleryItem item1">
<img id="image1" src="http://lorempixel.com/250/200/" alt="picture1">
</div>
<div class="galleryItem item2">
<img id="image2" src="http://lorempixel.com/250/200/" alt="picture2">
</div>
<div class="galleryItem item3">
<img id="image3" src="http://lorempixel.com/250/200/" alt="picture3">
</div>
<div class="galleryItem item4">
<img id="image4" src="http://lorempixel.com/250/200/" alt="picture4">
</div>
<div class="galleryItem item5">
<img id="image5" src="http://lorempixel.com/250/200/" alt="picture5">
</div>
<div class="galleryItem item6">
<img id="image6" src="http://lorempixel.com/250/200/" alt="picture6">
</div>
<div class="galleryItem item7">
<img id="image7" src="http://lorempixel.com/250/200/" alt="picture7">
</div>
<div class="galleryItem item8">
<img id="image8" src="http://lorempixel.com/250/200/" alt="picture8">
</div>
<div class="galleryItem item9">
<img id="image9" src="http://lorempixel.com/250/200/" alt="picture9">
</div>
</div>
I don't know JS at all so don't be too harsh.
Thanks in advance.
Remove the onload from your body element (Using DOMContentLoaded event instead it is less intrusive).
var imageList = ["http://lorempixel.com/250/200/", "http://lorempixel.com/250/150/"],
imageListCounter = 0,
imageEls;
function swapImages() {
var i = 0, len = imageEls.length;
for (i = 0; i < len; i++) {
imageEls[i].src = imageList[imageListCounter];
}
imageListCounter++;
if (imageListCounter > imageList.length - 1) {
imageListCounter = 0;
}
}
document.addEventListener('DOMContentLoaded', function(event) {
imageEls = document.querySelectorAll('.galleryItem img');
setInterval(swapImages, 1000);
});
What we are doing here is:
on document ready store all the image elements in imageEls
then start a timer, calling swapImages every 1 second
swapImages iterates over images and changes the .src to what is in the next one in imageList
when the imageListCounter reaches the end of imageList it resets to 0
So the complete html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Gallery</title>
<link rel="stylesheet" href="style.css">
<script>
var imageList = ["http://lorempixel.com/250/200/", "http://lorempixel.com/250/150/"],
imageListCounter = 0,
imageEls;
function swapImages() {
var i = 0, len = imageEls.length;
for (i = 0; i < len; i++) {
imageEls[i].src = imageList[imageListCounter];
}
imageListCounter++;
if (imageListCounter > imageList.length - 1) {
imageListCounter = 0;
}
}
document.addEventListener('DOMContentLoaded', function(event) {
imageEls = document.querySelectorAll('.galleryItem img');
setInterval(swapImages, 1000);
});
</script>
</head>
<body>
<div class="galleryWrapper">
<div class="galleryItem item1">
<img src="http://lorempixel.com/250/200/" alt="picture1">
</div>
<div class="galleryItem item2">
<img src="http://lorempixel.com/250/200/" alt="picture2">
</div>
<div class="galleryItem item3">
<img src="http://lorempixel.com/250/200/" alt="picture3">
</div>
<div class="galleryItem item4">
<img src="http://lorempixel.com/250/200/" alt="picture4">
</div>
<div class="galleryItem item5">
<img src="http://lorempixel.com/250/200/" alt="picture5">
</div>
<div class="galleryItem item6">
<img src="http://lorempixel.com/250/200/" alt="picture6">
</div>
<div class="galleryItem item7">
<img src="http://lorempixel.com/250/200/" alt="picture7">
</div>
<div class="galleryItem item8">
<img src="http://lorempixel.com/250/200/" alt="picture8">
</div>
<div class="galleryItem item9">
<img src="http://lorempixel.com/250/200/" alt="picture9">
</div>
</div>
</body>
</html>
Where you set the image name to image1, you can just change to 'image'+i+''
document.getElementById('image'+i+'').src = images[i];
for (var e = 1; e < 10; e++)
{
var ImgID = 'image' + e;
document.getElementById(ImgID).src = images[i];
}
If you were using jquery you could just do a foreach on all the img elements. but the above will work. if you have 9 images with the ID of image1, image2, image3... you get the idea.
write this code in your else block
var imgs = document.getElementsByTagName('img');
for(j=0;j<imgs.length;j++){
imgs[j].src = images[i];
}
i++;
instead of this
document.getElementByClassName('gallery').src = images[i];
i++;
Give all your images a class attribute with the same value.
assuming you use the value "imagetags", replace your document.getElementById() line with the following:
var elements = document.GetElementsByClassName("imagetags");
for (var elem in elements){
elements[elem].src = images[i];
}

Categories