JavaScript - periodically change "active" image - javascript

I have 4 pictures and want them to periodically change class (I have .active class, which is similar to hover).
.active,
.pic:hover{
position: absolute;
border: 1px solid black;
transform: scale(1.1);
transition: transform .2s;
}
Basically I need the first picture to have the class active and after some time change it so the next picture has the class and the first one lose it.
Is something like that even possible?
Picture in HTML:
<div class="products">
<a href="http://example.com/produkt1">
<img class="pic" src="image.jpg" alt="image" width="75" height="75">
</a>
</div>
and JS:
productIndex = 0;
slideshow();
function slideshow(){
var i;
var pic = document.getElementsByClassName("pic");
for(i = 0; i < pic.length; i++){
pic[i].className = pic[i].className.replace("active", "");
}
productIndex++;
if(productIndex > pic.length){
productIndex = 1;
}
pic[productIndex-1].className += active;
setInterval(slideshow, 2000);
}

You can use setInterval to run a function periodically that will change the active class. Something like this (psuedo-code):
var imageArray = [];
var activeIndex = 0;
setInterval(function(){
imageArray[activeIndex].removeClass('active');
activeIndex++;
activeIndex %= 4;
imageArray[activeIndex].addClass('active');
}, 5000);
The number value passed in as a parameter is how many milliseconds to wait before running the function again. In this example, 5 seconds will pass between the classes are changed.
setInterval Reference

This is ugly but it could work for super basic ... You just need to update the div blocks with images if necessary. Uses jquery...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<style>
div {
width:50px;
height:50px;
background-color: black;
margin-bottom:10px;
}
.active {
background-color: red;
}
</style>
</head>
<body>
<div id="pic1"></div>
<div id="pic2"></div>
<div id="pic3"></div>
<div id="pic4"></div>
<script>
let lastActive = 0;
setInterval(()=>{
$('div').removeClass('active');
if(lastActive === 0){
$('#pic1').addClass('active');
lastActive = 1;
}
else if(lastActive === 1){
$('#pic2').addClass('active');
lastActive = 2;
}
else if(lastActive === 2){
$('#pic3').addClass('active');
lastActive = 3;
}
else if(lastActive === 3){
$('#pic3').addClass('active');
lastActive = 4;
}
else if(lastActive === 4){
$('#pic1').addClass('active');
lastActive = 1;
}
}, 500)
</script>
</body>
</html>

Matt L. has a good point here. Your code has the setInterval inside your slideshow function, otherwise it's fine.
productIndex = 0;
slideshow();
function slideshow(){
var i;
var pic = document.getElementsByClassName("pic");
for(i = 0; i < pic.length; i++){
pic[i].className = pic[i].className.replace("active", "");
}
productIndex++;
if(productIndex > pic.length){
productIndex = 1;
}
pic[productIndex-1].className += active;
}
setInterval(slideshow, 2000);
could probably work. Matt's answer is a lot better, and I came up with something similar, which is testable on jsfiddle.

You could do it like this for example:
$(document).ready(function() {
setInterval(function() {
var active = $('.active');
active.nextOrFirst().addClass('active');
active.removeClass('active');
}, 3000);
});
$.fn.nextOrFirst = function(selector)
{
var next = this.next(selector);
return (next.length) ? next : this.prevAll(selector).last();
};
.active,
.pic:hover{
border: 1px solid black;
}
.pic {
width: 150px;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image-container">
<img class="pic active" src="https://via.placeholder.com/350x150">
<img class="pic" src="https://via.placeholder.com/350x150">
<img class="pic" src="https://via.placeholder.com/350x150">
<img class="pic" src="https://via.placeholder.com/350x150">
</div>
Edit:
This, instead of most other solutions, will work with any amount of items. To use it only on pictures just specify via selector in the function.

Checkout this working example. I've made use of a combination of setInterval and setTimeout.
$(window).ready(()=>{
// get all the images inside the image-container div
let $images = $('.image-container').find('.image');
let currImage = 0;
// execute this code every 2 seconds
window.setInterval(()=>{
// add the active class to the current image
$($images[currImage]).addClass('active');
setTimeout(()=>{
// execute the code here after 1.5 seconds
// remove the active class from the previous image
$($images[currImage-1]).removeClass('active');
}, 1500);
// make sure we don't go over the number of elements in the collection
currImage = currImage >= $images.length ? 0 : currImage + 1;
}, 2000);
});
.image.active {
border: thin solid blue;
}
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<div class="image-container" class="">
<img src="https://via.placeholder.com/200x200" class="image active">
<img src="https://via.placeholder.com/200x200" class="image">
<img src="https://via.placeholder.com/200x200" class="image">
<img src="https://via.placeholder.com/200x200" class="image">
</div>
Do make sure that the code in setTimeout will execute before the next interval. Meaning, the time set for setTimeout is always less than setInterval's :)

Yes it is possible:
function carousel() {
var images = document.querySelectorAll(".container img");
for(var i = 0; i < images.length; i++) {
if(images[i].classList.contains("active")) {
images[i].classList.remove("active");
if(i == images.length - 1) {
images[0].classList.add("active");
} else {
images[i + 1].classList.add("active");
}
break;
}
}
}
setInterval(carousel,1000);
img {
width: 100px;
margin-left: 10px;
transition: .2s;
}
.active {
transform: scale(1.1);
}
<div class="container">
<img src="https://i.stack.imgur.com/cb20A.png" class="active"/>
<img src="https://i.stack.imgur.com/cb20A.png"/>
<img src="https://i.stack.imgur.com/cb20A.png"/>
<img src="https://i.stack.imgur.com/cb20A.png"/>
</div>
You can then replace the .active class by whatever you want.

Related

Building a vanilla carousel - stuck on one peice of logic

Any mentorship or guidance would be most welcomed.
I am trying to make a vanilla JS carousel and I am so close to realising my objective to build one.
However; I cannot seem to get the prev or next buttons to move the carousel backwards or forwards. The buttons "work" they go up and down in value; they do not change the style. I can see that console logging the values.
I've tried passing the function back onto itself - however, I cannot think of a way of initialising the start frame; if that is the best way.
Adding the slideIndex value into the style rule doesn't work. What I get is if you keep on pressing "prev" for example; eventually, another frame randomly pops up below.
Any help would be very much welcomed.
On a side note - is there a better way to work with variable scoping; without everything requiring this?
'use strict';
function carousel(n) {
this.slideIndex = n;
this.slides = document.querySelectorAll('.homepage_carousel_wrapper .homepage_carousel');
[...this.slides].forEach(function(x) {
x.style.display = 'none';
});
this.slides[this.slideIndex-1].style.display = "flex";
this.prev = function(n) {
this.slideIndex += n;
if (this.slideIndex < 1) {
this.slideIndex = this.slides.length;
}
console.log(`${this.slideIndex}`);
this.slides[this.slideIndex].style.display = "flex";
}
this.next = function(n) {
this.slideIndex += n;
if (this.slideIndex > this.slides.length) {
this.slideIndex = 1;
}
console.log(`${this.slideIndex}`);
this.slides[this.slideIndex].style.display = "flex";
//carousel(this.slideIndex)
}
};
window.addEventListener('load', function() {
const hp_carousel = new carousel(3);
let carouselPrev = document.getElementById('carousel_prev');
carouselPrev.addEventListener('click', function(e){
hp_carousel.prev(-1);
e.preventDefault();
e.stopPropagation();
}, false);
let carouselNext = document.getElementById('carousel_next');
carouselNext.addEventListener('click', function(e){
hp_carousel.next(1);
e.preventDefault();
e.stopPropagation();
}, false);
});
.homepage_carousel:nth-child(1) {
background-color: red;
width: 100%;
height: 200px;
}
.homepage_carousel:nth-child(2) {
background-color: blue;
width: 100%;
height: 200px;
}
.homepage_carousel:nth-child(3) {
background-color: green;
width: 100%;
height: 200px;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>carousel</title>
</head>
<body>
<a id='carousel_prev'>prev</a>
<a id='carousel_next'>next</a>
<div class='homepage_carousel_wrapper'>
<div class='homepage_carousel'>
<h1>Frame 1</h1>
</div>
<div class='homepage_carousel'>
<h1>Frame 2</h1>
</div>
<div class='homepage_carousel'>
<h1>Frame 3</h1>
</div>
</div>
</body>
</html>
I have made some modifications to the HTML and CSS, and have rewritten most of the JavaScript.
Main Modifications
HTML
Changed the controls from links to buttons.
Moved the controls inside the carousel.
CSS
Removed repeated CSS.
JavaScript
Added spacing to make the code more readable.
Added a few comments to make the code easier to understand.
Modified the carousel constructor to allow multiple carousels to be made.
Moved the control event listeners inside the carousel constructor.
Replaced the prev() and next() functions with a changeSlide() function.
'use strict';
window.addEventListener('load', function() {
const hpCarousel = new carousel('homepage_carousel', 3);
});
function carousel(id, index) {
// Set slide index and get slides
this.slideIndex = index;
const carousel = document.getElementById(id);
this.slides = [...carousel.getElementsByClassName('slide')];
// Get controls and add event listeners
const prev = carousel.getElementsByClassName('prev')[0];
const next = carousel.getElementsByClassName('next')[0];
prev.addEventListener('click', () => {
this.changeSlide(-1);
});
next.addEventListener('click', () => {
this.changeSlide(1);
});
// Functions for managing slides
this.hideAll = function() {
this.slides.forEach(function(slide) {
slide.style.display = 'none';
});
}
this.show = function() {
this.hideAll();
this.slides[this.slideIndex - 1].style.display = 'flex';
}
this.changeSlide = function(amount) {
this.slideIndex += amount;
this.slideIndex = (this.slideIndex > this.slides.length) ? 1 :
(this.slideIndex < 1) ? this.slides.length : this.slideIndex;
this.show();
}
// Show the specified slide
this.show();
}
.slide {
width: 100%;
height: 200px;
}
.slide:nth-child(1) {
background-color: red;
}
.slide:nth-child(2) {
background-color: blue;
}
.slide:nth-child(3) {
background-color: green;
}
<div id='homepage_carousel'>
<button class='prev'>prev</button>
<button class='next'>next</button>
<div>
<div class='slide'>
<h1>Frame 1</h1>
</div>
<div class='slide'>
<h1>Frame 2</h1>
</div>
<div class='slide'>
<h1>Frame 3</h1>
</div>
</div>
</div>

adding a classList to each element at a time in a array - plain js

I'm new to javascript and I've been trying something that although basic i can't really seem to understand why it isn't working.
I have three images and one button. Everytime I click that same button i want one of the images to disappear (using classList to add a Css class of display: none).
I'm trying to use the for loop but when I click the button they disappear at the same time. I've tried to create a variable inside the loop to store the index value but it returns an error.
Help please !!! Thanks
\\ Js
window.onload = function(){
var button = document.querySelector("button");
var imgs = document.querySelectorAll("#imagens img");
button.addEventListener("click",function(){
for(var i=0; i<imgs.length; i++){
imgs[i].classList.add("hidden");
//var currentImg = this.imgs[i];
//currentImg.classList.add("hidden");
}
})
};
\\\ CSS
.hidden{
display:none;
}
#images{
width:400px;
height:200px;
margin:0 auto;
}
#images img{
width:110px;
height:100px;
}
button{
margin:100px auto;
}
\\\ HTML
<div id="images">
<img src="https://media.defense.gov/2018/Jul/11/2001941257/780/780/0/180711-F-EF974- 0115.JPG" alt="">
<img src="https://live.staticflickr.com/3267/2590079513_12e2c73226_b.jpg" alt="">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Poinsettia_tree.jpg/360px-Poinsettia_tree.jpg" alt="">
<div>
<button type="button">change</button>
</div>
</div>
You can use setTimeout for this requirement and update the for loop inside button click like:
for (var i = 0; i < imgs.length; i++) {
(function(index) {
setTimeout(function() {
imgs[index].classList.add("hidden");
}, i * 1500);
})(i);
}
This way hidden class would be added to one image at a time after a delay of 1500 ms.
The problem is that every time the button is clicked, you loop through all the images so you add to all of them the hidden class. What you need to do is to create a global variable that can store the index of the last image you hid.
And when you click the button, you add the hidden class to the image at the index + 1 then increment that index for the next image. You don't need to have a for loop for that.
You also mistyped in your query selector, it should be
var imgs = document.querySelectorAll("#images img");
instead of
var imgs = document.querySelectorAll("#imagens img");
So here's what you should have :
let index = -1;
window.onload = function(){
var button = document.querySelector("button");
var imgs = document.querySelectorAll("#images img");
button.addEventListener("click",function(){
index++;
imgs[index].classList.add("hidden");
})
};
.hidden {
display: none;
}
#images {
width: 400px;
height: 200px;
margin: 0 auto;
}
#images img {
width: 110px;
height: 100px;
}
button {
margin: 100px auto;
}
<div id="images">
<img src="https://media.defense.gov/2018/Jul/11/2001941257/780/780/0/180711-F-EF974- 0115.JPG" alt="">
<img src="https://live.staticflickr.com/3267/2590079513_12e2c73226_b.jpg" alt="">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Poinsettia_tree.jpg/360px-Poinsettia_tree.jpg" alt="">
<div>
<button type="button">change</button>
</div>
</div>

Showing an element for 5 seconds, then hide and show next element

This is what I've tried so far, but it just shows all the elements at once:
i1 = document.getElementById('img_1');
i2 = document.getElementById('img_2');
i3 = document.getElementById('img_3');
i4 = document.getElementById('img_4');
i5 = document.getElementById('img_5');
myarr = [i1,i2,i3,i4,i5];
for (i=0; i<myarr.length;i++) {
$(myarr[i]).show().delay(5000).fadeOut();
}
I assume you are trying to achieve an endless loop.
I think you should use interval in that case, and do fadeOut/fadeIn of elements.
i1 = document.getElementById('img_1');
i2 = document.getElementById('img_2');
i3 = document.getElementById('img_3');
i4 = document.getElementById('img_4');
i5 = document.getElementById('img_5');
let myarr = [i1, i2, i3, i4, i5];
let active = 1;
setInterval(() => {
$(myarr[active - 1]).fadeOut(500)
if (active >= myarr.length) {
active = 0
}
setTimeout(() => {
$(myarr[active]).fadeIn(500);
active = active + 1;
}, 500)
}, 5000)
What this does, is updates elements every 5 sec to next element, if it reached the end, it resets it to zero.
Checkout this fiddle
You can use async and await.
Another this you can improve is that. You can add same class to all images you want to show in series. If you want to select all by id you can use Attribute Selectors.
const myarr = document.querySelectorAll('img[id^=img]');
I have used same class rather than id
const arr = [...document.querySelectorAll('.test')];
(async function(){
for (let i=0; i<arr.length;i++) {
await new Promise(res => {
setTimeout(() => {
$(arr[i]).show().fadeOut();
res();
},2000)
})
}
})()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test">Test 1</div>
<div class="test">Test 2</div>
<div class="test">Test 3</div>
let count = 1;
setInterval(()=>{
document.querySelectorAll("*[id*='img_']").forEach((elem)=> elem.style.display="none");
document.getElementById(`img_${count}`).style.display="";
if(count<4) count++;
else count = 1;
},1000)
<div id="img_1">Image 1</div>
<div id="img_2" style="display:none">Image 2</div>
<div id="img_3" style="display:none">Image 3</div>
<div id="img_4" style="display:none">Image 4</div>
Vanilla Javascript solution!
You forgot to show your element after fadeOut. Here you can achieve it:
// show first element
$('img').eq(0).show();
$('img').each(function () {
// your delay
$('img').delay(5000).fadeOut();
// make sure next element is image
if ($(this).next()[0].tagName === 'IMG') {
// show next element
$(this).next().fadeIn();
}
});
img {
display: none;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://picsum.photos/id/5/50" />
<img src="https://picsum.photos/id/10/50" />
<img src="https://picsum.photos/id/30/50" />
<img src="https://picsum.photos/id/0/50" />
<img src="https://picsum.photos/id/150/50" />
<img src="https://picsum.photos/id/1000/50" />
var basicVal =0;
$(document).ready(function(){
$('.wrapper img').eq( basicVal ).show();
var setTime =setInterval(function(){
if( basicVal < $('.wrapper img').length - 1){
$('.wrapper img').eq(basicVal ).hide();
basicVal++;
$('.wrapper img').eq(basicVal).show();
}else{
clearTimeout(setTime);
}
console.log();
}, 5000);
});
.wrapper{
width: 100%;
float: left;
}
.wrapper img{
width: 50%;
height: 300px;
object-fit: cover;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<img src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="">
<img src="http://www.desktopwallpaperhd.net/wallpapers/0/4/landscapes-wallpaper-fengguangbizhi-fengjingbizhi-picture-image-1316.jpg" alt="">
<img src="http://trustbanksuriname.com/wp-content/uploads/2019/04/pony-picture-guide-to-native-pony-breeds-little-pony-cartoon-pictures.jpg" alt="">
<img src="https://www.bigfoto.com/stones-background.jpg" alt="">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQulscf1nNOpaI1tElZgKTTSAl_ZcL_i1VwLDojgKzqjSTMofsqPw" alt="">
</div>
check this out I use some little bit of jquery and setInterval function to change in every 5000ms
You may use setTimeout for achieving this effect.
<div id="container">
<div class="block" id="img_1"></div>
<div class="block" id="img_2"></div>
<div class="block" id="img_3"></div>
<div class="block" id="img_4"></div>
<div class="block" id="img_5"></div>
</div>
.block{
width:100px;
height:100px;
display: inline-block;
margin:10px;
background: lightblue;
visibility: hidden;
}
And then,
$('.block').each(function(index, value) {
setTimeout(function() {
$(value).css("visibility", "visible");
$(value).show().delay(1000).fadeOut();
}, 2000 * (index + 1));
});

z-Index slide show using the next button

So I have to code a button that uses z-index to go to the next picture in the slideshow. I am having difficulty trying to get it to work and I feel as though I am doing something wrong. It has to have a count of 0, 1, 2, 0, 1, 2
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Lab 5, Part 1</title>
<meta charset = "utf-8"/>
<script type = "text/javascript">
function Next() {
document.getElementById('anime1').style.zIndex = 0;
document.getElementById('anime2').style.zIndex = 1;
document.getElementById('anime3').style.zIndex = 2;
}
</script>
<style type = "text/css">
.anime1 {position: absolute;
top: 150px; left: 250px; z-index: 10;}
.anime2 {position: absolute;
top: 200px; left: 300px; z-index: 15;}
.anime3 {position: absolute;
top: 250px; left: 350px; z-index: 20;}
</style>
</head>
<body>
<h1 style= "text-align: center">Lab 5, Part 1</h1>
<p>
<div class="slideshow">
<img class = "anime1" id = "anime1" height = "300"
width = "450" src = "http://images5.fanpop.com/image/photos/29300000/Megurine-Luka-megurine-luka-29391390-1680-1050.jpg"
alt = "First Image"/>
<img class = "anime2" id = "anime2" height = "300"
width = "450" src = "http://orig06.deviantart.net/a28f/f/2015/079/9/a/hinata_final_lr_by_artgerm-d8me6vb.jpg"
alt = "Second Image"/>
<img class = "anime3" id = "anime3" height = "300"
width = "450" src = "http://images6.fanpop.com/image/photos/35700000/Hatsune-Miku-snowangel_-35736242-1600-1200.jpg"
alt = "Third Image"/>
</p>
<input type="button" value="Next" onclick="Next();">
</body>
</html>
I have looked every where online to see if anything could help me but I can't find anything
If you're willing to take a more programmatic approach, you can use an array to hold the order and iterate it to set the z-indexes.
Using this method you can
pop() the item from the end of the array and unshift() it onto the beginning, or
shift() the item from the beginning of the array and push() it onto the end.
Which allows you to easily handle any number of elements while keeping your code DRY.
I've taken the liberty of making a back button as well as the next button, to show you how easy it is when approaching it this way. I've also generalized the class names and used different placeholder images for the demo.
(function(){ // keep it safe
var slideshow = document.querySelector('.slideshow'); // store the parent
var controls = slideshow.querySelector('.controls'); // store the controls
var els = slideshow.querySelectorAll('.slide'); // store the slides
var order = Object.keys(els); // store the order
var cn; // make the class holder
// assign a click handler to the parent
controls.onclick = function(e) {
// if the class is back or next, store it, otherwise stop here
if(!(cn = (e.target.className.match(/back|next/)||[false])[0])) return;
// if back clicked, move the last element to the beginning
if(cn === "back") order.unshift(order.pop());
// if next clicked, move the first element to the end
if(cn === "next") order.push(order.shift());
// iterate the order, set the z-index of each element sequentially
for(var i in order) els[order[i]].style.zIndex = i;
}
})();
.slides { position: relative; margin-top: 5px; }
.slide { position: absolute; }
.slide2 { top: 25px; left: 25px; }
.slide3 { top: 50px; left: 50px; }
<div class="slideshow">
<div class="controls">
<button class="back">Back</button>
<button class="next">Next</button>
</div>
<div class="slides">
<img class="slide slide1" src="http://placehold.it/150x150/f9fd42/fff">
<img class="slide slide2" src="http://placehold.it/150x150/42f9fd/fff">
<img class="slide slide3" src="http://placehold.it/150x150/fd42f9/fff">
</div>
</div>
Further Reading
Array.prototype.pop() (MDN)
Array.prototype.unshift() (MDN)
Array.prototype.shift() (MDN)
Array.prototype.push() (MDN)
Don't Repeat Yourself (Wikipedia)
Are you looking for something like this: https://jsfiddle.net/5L7jk73g/
var cnt = 0;
function Next() {
if (cnt == 0) {
document.getElementById('anime1').style.zIndex = 0;
document.getElementById('anime2').style.zIndex = 1;
document.getElementById('anime3').style.zIndex = 2;
cnt++;
} else if (cnt == 1) {
document.getElementById('anime1').style.zIndex = 1;
document.getElementById('anime2').style.zIndex = 2;
document.getElementById('anime3').style.zIndex = 0;
cnt++;
} else {
document.getElementById('anime1').style.zIndex = 2;
document.getElementById('anime2').style.zIndex = 0;
document.getElementById('anime3').style.zIndex = 1;
cnt = cnt - 2;
}
}

JS Slideshow with Next button

I want my code to act like a slideshow. If I click the next button it will hide the previous image and show the other image. It will show the first image, but it doesn't' go through the loop . I also have an error that say
"Uncaught TypeError: Cannot read property 'style' of undefined".
<!DOCTYPE html>
<html lang ="en">
<head>
<title> VIS</title>
<meta charset="utf-8"/>
</head>
<body>
<div style="position: relative; visibility: hidden;">
<img src="http://vignette4.wikia.nocookie.net/mrmen/images/5/52/Small.gif/revision/latest?cb=20100731114437"
alt="Pumpkins" id="Pum"/>
</div>
<div style="position: relative; visibility: hidden;">
<img src="http://vignette4.wikia.nocookie.net/mrmen/images/5/52/Small.gif/revision/latest?cb=20100731114437"
alt="Pumpkins" id="Straw"/>
</div>
<div style="position: relative; visibility: hidden;">
<img src="http://vignette4.wikia.nocookie.net/mrmen/images/5/52/Small.gif/revision/latest?cb=20100731114437"
alt="Pumpkins" id="Ras"/>
</div>
<button onclick="removeVisibility()">Next</button>
</body>
<script type="text/javascript" >
function removeVisibility(){
var imgs=document.getElementsByTagName('img');//get all the images
for(var i=0;i< imgs.length;i++){
imgs[i].style.visibility= 'visible'; //hide them
imgs[i-1].style.visibility= 'hidden';
}
}
</script>
</html>
jsBin demo
You have your DIV (!!!) elements set to visibility: hidden; but you're trying desperately to change the visibility to IMG.
Now that you know your main issue, you should better go with display none/block if you use position:relative (or rather use position: absolute for your overlaying elements...) Any way,
don't use inline CSS styles! That's why we invented stylesheets!
don't use inline JS! Use addEventListener to attach any desired event to your elements. Don't mix your application logic with (view) teplating.
var imagesHolder = document.getElementById("imagesHolder");
var images = imagesHolder.getElementsByTagName('img');
var imagesTot = images.length;
var button = document.getElementById("nextImage");
var counter = 0; // We'll use it to get the image index
function showNext(){
counter = ++counter % imagesTot; // Increment and loop counter
for(var i=0; i<imagesTot; i++){
if(i != counter) images[i].style.display = "none"; // Hide all but `counter` one
}
// Finally show the 'counter' one!
images[counter].style.display = "block";
}
button.addEventListener("click", showNext);
#imagesHolder img+img{ /* SHOW ALL BUT FIRST!*/
display:none;
}
<div id="imagesHolder">
<img src="http://lorempixel.com/400/200/sports/1" alt="1"/>
<img src="http://lorempixel.com/400/200/sports/2" alt="2"/>
<img src="http://lorempixel.com/400/200/sports/3" alt="3"/>
</div>
<button id="nextImage">Next</button>
...but wait!
Welcome to the world of responsive web design!
so let's add some animations and responsiveness:
var imagesHolder = document.getElementById("imagesHolder"),
images = imagesHolder.getElementsByTagName('div'),
n = images.length,
c = 0;
function showNext(){
c = ++c % n;
for(var i=0; i<n; i++) images[i].classList[i!=c?"add":"remove"]("fadeaway");
}
document.getElementById("nextImage").addEventListener("click", showNext);
showNext(); // Initial kick
*{margin:0;}
html, body{height:100%;}
#imagesHolder{
position:relative;
overflow:hidden;
width:100%;
height:90vh;
}
#imagesHolder div{
position: absolute;
width:inherit;
height:inherit;
background:50% / cover;
transition: 1s 0s ease;
/* Default when visible: */
opacity: 1;
transform: scale(1);
}
#imagesHolder div.fadeaway{
opacity:0;
transform: scale(1.2);
}
<div id="imagesHolder">
<div style="background-image:url(http://lorempixel.com/400/200/sports/1);"></div>
<div style="background-image:url(http://lorempixel.com/400/200/sports/2);"></div>
<div style="background-image:url(http://lorempixel.com/400/200/sports/3);"></div>
</div>
<button id="nextImage">Next</button>

Categories