Simple JS carousel need advice - javascript

I am trying to create a simple carousel with JavaScript, I am having one issue, how can I display the slides, based on the startingPosition value?
const items = document.getElementsByClassName("carousel__item")
let startingPosition = 0;
let totalItems = items.length;
const prevButton = document.querySelector(".prev")
const nextButton = document.querySelector(".next")
prevButton.addEventListener("click", () => {
if(startingPosition == 0) return;
startingPosition--;
}
);
nextButton.addEventListener("click", () => {
startingPosition++;
if(startingPosition == totalItems) {
startingPosition = 0;
}
}
);
.carousel {
max-width: 400px;
margin: 0 auto;
}
.carousel__item > img {
width: 100%;
}
<div class="carousel">
<div class="carousel__item">
<img src="https://www.greenqueen.com.hk/wp-content/uploads/2021/06/WEF-Investments-In-Nature-Based-Solutions-Have-To-Triple-By-2030-To-Address-Climate-Change-Biodiversity-Loss.jpg" />
</div>
<div class="carousel__item">
<img src="https://tr-images.condecdn.net/image/LDM0pgM40l1/crop/2040/f/gettyimages-1146431497.jpg" />
</div>
</div>
<button class="prev">
Prev
</button>
<button class="next">
Next
</button>

You need to write function to show the active image based on startingPosition.
showSlides does the same thing. It goes through all carousel__item and hide all of them and show only the picture in startingPosition position.
const items = document.getElementsByClassName("carousel__item")
let startingPosition = 0;
let totalItems = items.length;
showSlides(startingPosition);
const prevButton = document.querySelector(".prev")
const nextButton = document.querySelector(".next")
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("carousel__item");
if (n > slides.length) { startingPosition = 1 }
if (n < 1) { startingPosition = slides.length }
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slides[startingPosition - 1].style.display = "block";
}
prevButton.addEventListener("click", () => {
if (startingPosition == 0) return;
startingPosition--;
showSlides(startingPosition);
}
);
nextButton.addEventListener("click", () => {
startingPosition++;
if (startingPosition == totalItems) {
startingPosition = 0;
}
showSlides(startingPosition);
});
.carousel {
max-width: 400px;
margin: 0 auto;
}
.carousel__item > img {
width: 250px;
height: 150px;
}
<div class="carousel">
<div class="carousel__item">
<img src="https://www.w3schools.com/howto/img_lights_wide.jpg" />
</div>
<div class="carousel__item">
<img src="https://tr-images.condecdn.net/image/LDM0pgM40l1/crop/2040/f/gettyimages-1146431497.jpg" />
</div>
</div>
<button class="prev">
Prev
</button>
<button class="next">
Next
</button>

Related

Carousel js. Slider doesn't work.How to make it work correctly?

I think I made a mistake in js code because it doesn't work when I click . There are no actions . What should I change in js code?Thanks. My js code:
const slides = document.querySelector(".slides");
const slidesCount = slides.childElementCount;
console.log(slidesCount)
const nextBtn=document.querySelector(".next-slide");
const prevBtn=document.querySelector(".prev-slide");
const container = document.querySelector('.slider-container')
//Controls
prevBtn.addEventListener('click', () => {
changeSlide('prev')
})
nextBtn.addEventListener('click', () => {
changeSlide('next')
})
let activeSlideIndex = 0
function changeSlide(direction) {
if(direction === 'prev') {
activeSlideIndex++
if(activeSlideIndex === slidesCount) {
activeSlideIndex = 0
}
} else if(direction === 'next') {
activeSlideIndex--
if(activeSlideIndex < 0) {
activeSlideIndex = slidesCount - 1
}
}
}
Here my html code.
<button class="prev-slide">◁</button>
<button class="next-slide">▷</button>
</div>
<div class="slides">
<img class="slide" src="images/picture1.jpg" alt="slide image">
<img class="slide" src="images/picture2.jpg" alt="slide image">
<img class="slide" src="images/picture3.jpg" alt="slide image">
</div>
I think the only thing missing was the actual rendering. You have to somehow hide or show the active slide. I've done that by adding active class and only showing that (through CSS). Then your changeSlide function does not only calculate the active slide, but also set the class on the appropriate element.
const slides = document.querySelector(".slides");
const slidesCount = slides.childElementCount;
console.log(`Showing ${slidesCount} slides.`)
const nextBtn=document.querySelector(".next-slide");
const prevBtn=document.querySelector(".prev-slide");
const container = document.querySelector('.slider-container')
//Controls
prevBtn.addEventListener('click', () => {
changeSlide('prev')
})
nextBtn.addEventListener('click', () => {
changeSlide('next')
})
let activeSlideIndex = 0
function changeSlide(direction) {
if(direction === 'prev') {
activeSlideIndex++
if(activeSlideIndex === slidesCount) {
activeSlideIndex = 0
}
} else if(direction === 'next') {
activeSlideIndex--
if(activeSlideIndex < 0) {
activeSlideIndex = slidesCount - 1
}
}
Array.from(slides.children).forEach((slide, idx) => {
if (idx === activeSlideIndex) {
slide.classList.add('active');
} else {
slide.classList.remove('active');
}
});
}
.controls {
margin-bottom: 2em;
}
.slides .slide {
display: none
}
.slides .slide.active {
display: block;
}
<section class="controls">
<button class="prev-slide">◁</button>
<button class="next-slide">▷</button>
</section>
<div class="slides">
<img class="slide active" src="https://via.placeholder.com/450x250" alt="slide image">
<img class="slide" src="https://loremflickr.com/640/250" alt="slide image">
<img class="slide" src="https://www.fillmurray.com/640/250" alt="slide image">
</div>

Button array is empty after I copied from another array that has the whole set of HTMLCollection

I want to store all the existing button names into an array(copyAllButtons) by using the push function.
However, after the for-loop, there is still nothing inside copyAllButtons.
I am trying to make a reset function that required the array(copyAllButtons) to restore all the button names saved.
Can anyone help me? Thank you.
var all_buttons = document.getElementsByTagName('button'); //all button names are saved
var copyAllButtons = [];
console.log(all_buttons);
for (let i = 0; i < all_buttons.length; i++) {
copyAllButtons.push(all_buttons[i].classList[1]);
}
console.log(copyAllButtons); //####Button array is empty####
This is my file:
https://drive.google.com/file/d/1qbAAHClxJhNQUFyvrSklbGwX9tbsEsL8/view?usp=sharing
message of console.log(copyAllButtons)
element inside all_buttons
code related:JS
//challenge4
var all_buttons = document.getElementsByTagName('button'); //all button names are saved
var copyAllButtons = [];
console.log(all_buttons);
for (let i = 0; i < all_buttons.length; i++) {
copyAllButtons.push(all_buttons[i].classList[1]);
}
console.log(copyAllButtons); //####Button array is empty####
function buttonColorChange(buttonThingy) {
if (buttonThingy.value === 'red') {
buttonsRed();
} else if (buttonThingy.value === 'green') {
buttonsGreen();
} else if (buttonThingy.value === 'reset') {
buttonsColorReset();
} else if (buttonThingy.value === 'random') {
randomColors();
}
}
function buttonsRed() {
for (let i = 0; i < all_buttons.length; i++) {
all_buttons[i].className = 'btn btn-danger';
}
}
function buttonsGreen() {
for (let i = 0; i < all_buttons.length; i++) {
all_buttons[i].className = 'btn btn-success';
}
}
function buttonsColorReset() { //##function that i am working on##
for (let i = 0; i < all_buttons.length; i++) {
all_buttons[i].classList.remove(all_buttons[i].classList[1]);
all_buttons[i].classList.add(copyAllButtons[i]);
}
}
function randomColors() {
for (let i = 0; i < all_buttons.length; i++) {
var x = Math.floor(Math.random() * 4);
var y = ['btn-primary', 'btn-danger', 'btn-warning', 'btn-success'];
all_buttons[i].className = 'btn ' + y[x];
}
}
HTML
<div class="container-4">
<h2 id="change-my-color">Challenge 4:Change the color of all buttons</h2>
<div class="flex-box-pick-color">
<form action="">
<select name="backdrop" id="background" onChange="buttonColorChange(this)">
<option value="random">Random</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="reset">Reset</option>
</select>
</form>
<button class="btn btn-primary">Wee!</button>
<button class="btn btn-danger">Yahoo!</button>
<button class="btn btn-warning">Google!</button>
<button class="btn btn-success">Facebook!</button>
</div>
</div>
CSS:
.container-1, .container-2 , .container-3 ,.container-4{
border: 1px solid blue;
width:75%;
margin: 0 auto;
text-align: center;
}
.flex-box-container-1, .flex-box-container-2,.flex-box-rps,.flex-box-pick-color{
display:flex;
border:1px solid purple;
padding: 10px;
flex-wrap:wrap;
flex-direction: row;
justify-content: space-around;
}
All my code for reference:
javascript:
function ageInDays() {
var birthYear = prompt("What year were you born?")
var days = (2021 - birthYear) * 365
var h1 = document.createElement('h1')
var textAnswer = document.createTextNode('You are ' + days + ' days old')
h1.setAttribute('id', 'days');
h1.appendChild(textAnswer)
document.getElementById('flex-box-result').appendChild(h1)
}
function reset() {
document.getElementById('days').remove()
}
function generateCat() {
var image = document.createElement('img');
var div = document.getElementById('flex-cat-gen');
image.src = "https://thecatapi.com/api/images/get?format=src&type=gif&size=small";
div.appendChild(image);
}
//challenge3 rock paper scissors
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function randToRpsInt() {
return Math.floor(Math.random() * 3);
}
function numberToChoice(number) {
return ['rock', 'paper', 'scissors'][number]
}
function rpsGame(yourChoice) {
var result;
console.log(yourChoice.id);
var humanChoice, botChoice;
var message
humanChoice = yourChoice.id;
botChoice = numberToChoice(randToRpsInt());
console.log(botChoice);
if (humanChoice === 'rock') {
if (botChoice === 'rock') {
result = "tie"
console.log("tie");
}
else if (botChoice === 'paper') {
result = "lost"
console.log("You Lost>_<");
}
else {
result = "win"
console.log("You Win OAO");
}
}
else if (humanChoice === 'paper') {
if (botChoice === 'rock') {
result = "win";
console.log("You Win OAO");
}
else if (botChoice === 'scissors') {
result = "lost";
console.log("You Lost>_<");
}
else {
result = "tie";
console.log("tie");
}
}
//scissors
else {
if (botChoice === 'paper') {
result = "win";
console.log("You Win OAO");
}
else if (botChoice === 'rock') {
result = "lost";
console.log("You Lost>_<");
}
else {
result = "tie";
console.log("tie");
}
}
message = finalMessage(result);
rpsFrontEnd(humanChoice, botChoice, message);
}
function finalMessage(result) {
if (result === "lost")
return { 'message': 'You lost!', 'color': 'red' };
else if (result === "win")
return { 'message': 'You won!', 'color': 'green' };
else
return { 'message': 'You tied!', 'color': 'yellow' };
}
function rpsFrontEnd(humanImageChoice, botImageChoice, finalMessage) {
var imagesDatabase = {
'rock': document.getElementById('rock').src,
'paper': document.getElementById('paper').src,
'scissors': document.getElementById('scissors').src
}
document.getElementById('rock').remove();
document.getElementById('paper').remove();
document.getElementById('scissors').remove();
var humanDiv = document.createElement('div');
var botDiv = document.createElement('div');
var messageDiv = document.createElement('div');
humanDiv.innerHTML = "<img src='" + imagesDatabase[humanImageChoice] + "' height=150 width=150 style='box-shadow: 0px 10px 50px rgba(37,50,233,1);'>"
botDiv.innerHTML = "<img src='" + imagesDatabase[botImageChoice] + "' height=150 width=150 style='box-shadow: 0px 10px 50px rgba(3243,38,24,1);'>"
messageDiv.innerHTML = "<h1 style='color: " + finalMessage['color'] + "; font-size: 60px;padding:30px; '>" + finalMessage['message'] + "</h1>"
document.getElementById('flex-box-rps-div').appendChild(humanDiv);
document.getElementById('flex-box-rps-div').appendChild(messageDiv);
document.getElementById('flex-box-rps-div').appendChild(botDiv);
}
//challenge4
var all_buttons = document.getElementsByTagName('button'); //all button names are saved
var copyAllButtons = [];
console.log(all_buttons);
for (let i = 0; i < all_buttons.length; i++) {
copyAllButtons.push(all_buttons[i].classList[1]);
}
console.log(copyAllButtons); //####Button array is empty####
function buttonColorChange(buttonThingy) {
if (buttonThingy.value === 'red') {
buttonsRed();
} else if (buttonThingy.value === 'green') {
buttonsGreen();
} else if (buttonThingy.value === 'reset') {
buttonsColorReset();
} else if (buttonThingy.value === 'random') {
randomColors();
}
}
function buttonsRed() {
for (let i = 0; i < all_buttons.length; i++) {
all_buttons[i].className = 'btn btn-danger';
}
}
function buttonsGreen() {
for (let i = 0; i < all_buttons.length; i++) {
all_buttons[i].className = 'btn btn-success';
}
}
function buttonsColorReset() { //##function that i am working on##
for (let i = 0; i < all_buttons.length; i++) {
all_buttons[i].classList.remove(all_buttons[i].classList[1]);
all_buttons[i].classList.add(copyAllButtons[i]);
}
}
function randomColors() {
for (let i = 0; i < all_buttons.length; i++) {
var x = Math.floor(Math.random() * 4);
var y = ['btn-primary', 'btn-danger', 'btn-warning', 'btn-success'];
all_buttons[i].className = 'btn ' + y[x];
}
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<title>challenge game</title>
</head>
<body>
<script src="home.js"></script>
<div class="container-1">
<h2>Challenge 1: Your Age in Days</h2>
<div class="flex-box-container-1">
<div> <button class="btn btn-primary" onclick="ageInDays()">Click Me</button></div>
<div> <button class="btn btn-danger" onclick="reset()">Reset</button></div>
</div>
</div>
<div class="flex-box-container-1">
<div id="flex-box-result">
</div>
</div>
<div class="container-2">
<h2>Challenge 2: Cat Generator</h2>
<button class="btn btn-success" id="cat-generator" onClick="generateCat()">Generate Cat</button>
<div class="flex-box-container-2" id="flex-cat-gen">
</div>
</div>
<div class="container-3">
<h2>Challenge 3:Rock,Paper,Scissors</h2>
<div class="flex-box-rps" id="flex-box-rps-div">
<img id="rock" src="https://cdn.drawception.com/images/panels/2017/2-4/wqmCPbxybn-4.png" alt=""
onClick="rpsGame(this)" width="250" height="250">
<img id="paper" src="https://sc04.alicdn.com/kf/UTB8apntp0nJXKJkSaiyq6AhwXXaR.jpg" alt="" onClick="rpsGame(this)"
width="250" height="250">
<img id="scissors" src="https://www.collinsdictionary.com/images/full/scissors_100136453.jpg" alt=""
onClick="rpsGame(this)" width="250" height="250">
</div>
</div>
<div class="container-4">
<h2 id="change-my-color">Challenge 4:Change the color of all buttons</h2>
<div class="flex-box-pick-color">
<form action="">
<select name="backdrop" id="background" onChange="buttonColorChange(this)">
<option value="random">Random</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="reset">Reset</option>
</select>
</form>
<button class="btn btn-primary">Wee!</button>
<button class="btn btn-danger">Yahoo!</button>
<button class="btn btn-warning">Google!</button>
<button class="btn btn-success">Facebook!</button>
</div>
</div>
</body>
</html>
CSS:
.container-1, .container-2 , .container-3 ,.container-4{
border: 1px solid blue;
width:75%;
margin: 0 auto;
text-align: center;
}
.flex-box-container-1, .flex-box-container-2,.flex-box-rps,.flex-box-pick-color{
display:flex;
border:1px solid purple;
padding: 10px;
flex-wrap:wrap;
flex-direction: row;
justify-content: space-around;
}
.flex-box-container-1 div{
display:flex;
padding: 10px;
border: 1 px solid black;
align-items: center;
}
.flex-box-container-2 img{
margin:10px;
box-shadow: 0px 10px 50px rgba(0,0,0,0.7);
}
.flex-box-rps img:hover{
box-shadow: 0px 10px 50px rgba(37,50,233,1);
}
Map button properties to a new array for later use, a minimal reproducable example.
// map button.btn properties to strings with id and class list
const all_buttons = [...document.querySelectorAll('button.btn')]
.map(b => `button#${b.id}, class: ${[...b.classList].join(', ')}`);
console.log(all_buttons);
// so ...
// save original classNames
const initialButtonClasses = [...document.querySelectorAll('button')]
.map(bttn => [...bttn.classList]);
// replacement classes
const green = [`btn`, `green`];
document.addEventListener(`click`, handle);
function handle(evt) {
if (evt.target.dataset.reset) {
return document.querySelectorAll('button.btn')
.forEach((btn, i) => {
btn.classList.remove(...btn.classList);
btn.classList.add(...initialButtonClasses[i]);
});
}
if (evt.target.dataset.green) {
return document.querySelectorAll('button.btn')
.forEach((btn, i) => {
btn.classList.remove(...btn.classList);
btn.classList.add(...green);
});
}
}
.green {
color: green;
}
<button id="a" class="btn z">bttnA</button>
<button id="b" class="btn y">bttnB</button>
<button id="c" class="btn x">bttnC</button>
<button data-green="1">all green</button>
<button data-reset="1">reset</button>
After searching for a long time, I found that I made a mistake in index.html, script tag should be put at the end of the body.

JS Image Slider with specific text to each image

I've followed a tutorial about JS image sliders. I'm trying to have a text box display on each image (figured that out) but I need the text to be specific for each image. The images being grabbed from an img folder and are in order (image-0, image-1, etc). I'm guessing I'll need some array but I can't figure out how to do this in JS and have the corresponding text display on each correct image. Code provided. Any help?
HTML
<body>
<div class="images">
<div id="btns">
<button type="button" class="btn prevBtn">↩</button>
<button type="button" class="btn nextBtn">↪</button>
</div>
<div id="textBlock">
<h4>This is the image</h4>
</div>
</div>
<script src="script.js"></script>
</body>
JS
const nextBtn = document.querySelector(".nextBtn");
const prevBtn = document.querySelector(".prevBtn");
const container = document.querySelector(".images");
let counter = 0;
nextBtn.addEventListener("click",nextSlide);
prevBtn.addEventListener("click",prevSlide);
function nextSlide () {
container.animate([{opacity:"0.1"},{opacity:"1.0"}],{duration:1000,fill:"forwards"});
if(counter === 4){
counter = -1;
}
counter++;
container.style.backgroundImage = `url(img/image-${counter}.jpg`
}
function prevSlide () {
container.animate([{opacity:"0.1"},{opacity:"1.0"}],{duration:1000,fill:"forwards"});
if(counter === 0){
counter = 5;
}
counter--;
container.style.backgroundImage = `url(img/image-${counter}.jpg`
}
Since you counter is indexed 0 and goes up to 𝑛 all you need is an array:
const descriptions = [
"A nice walk in the park", // for the image counter 0
"My dog and me", // for the image counter 1
// etc.
];
than all you need to do is:
textBlock.textContent = descriptions[counter];
But...
I don't know where you found that toturial but it's a really a great example on how not to build a gallery. The animation is odd, it's overly simplistic and cannot account for multiple galleries. It's repetitive and unmodular. And the total number of slides should never be hardcoded, that's why we use a programming language after all. And yes, it can count the number of items using .length.
Code should be reusable:
class Gallery {
constructor(id, slides) {
this.slides = slides || [];
this.total = this.slides.length;
this.curr = 0;
this.EL = document.querySelector(id);
this.EL_area = this.EL.querySelector(".Gallery-area");
this.EL_prev = this.EL.querySelector(".Gallery-prev");
this.EL_next = this.EL.querySelector(".Gallery-next");
this.EL_desc = this.EL.querySelector(".Gallery-desc");
const NewEL = (tag, prop) => Object.assign(document.createElement(tag), prop);
// Preload images
this.ELs_items = this.slides.reduce((DF, item) => (DF.push(NewEL("img", item)), DF), []);
this.EL_area.append(...this.ELs_items);
// Events
this.EL_prev.addEventListener("click", () => this.prev());
this.EL_next.addEventListener("click", () => this.next());
// Init
this.anim();
}
// Methods:
anim() {
this.curr = this.curr < 0 ? this.total - 1 : this.curr >= this.total ? 0 : this.curr;
this.ELs_items.forEach((EL, i) => EL.classList.toggle("is-active", i === this.curr));
this.EL_desc.textContent = this.slides[this.curr].alt;
}
prev() {
this.curr -= 1;
this.anim();
}
next() {
this.curr += 1;
this.anim();
}
}
// Use like:
new Gallery("#gallery-one", [
{alt: "My fluffy dog and me", src: "https://picsum.photos/400/300"},
{alt: "Here, we seem happy!", src: "https://picsum.photos/300/300"},
{alt: "We are making pizza?", src: "https://picsum.photos/600/300"},
]);
.Gallery {
position: relative;
height: 300px;
max-height: 100vh;
}
.Gallery-area > * {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
object-fit: cover;
transition: opacity 0.3s;
opacity: 0;
}
.Gallery-area > *.is-active {
opacity: 1;
}
.Gallery-btns {
position: absolute;
bottom: 20px;
width: 100%;
text-align: center;
}
.Gallery-desc {
position: absolute;
top: 20px;
width: 100%;
text-align: center;
font-size: 3em;
}
<div class="Gallery" id="gallery-one">
<div class="Gallery-area"></div>
<div class="Gallery-btns">
<button type="button" class="btn Gallery-prev">←</button>
<button type="button" class="btn Gallery-next">→</button>
</div>
<div class="Gallery-desc"></div>
</div>

Autoplay on slider doesn't play after showing next div

I want to have an autoplay in my slider but I encounter a problem. After showing next div it doesn't continue to show another div.
How can I fix this?
Here is my code:
<div class="container">
<div class="mySlides active" style="background-image: url('images/1.jpg')">
</div>
<div class="mySlides" style="background-image: url('images/2.jpg');">
</div>
<div class="mySlides" style="background-image: url('images/3.jpg');">
</div>
</div>
<script>
var currentSlide = 1;
var isPlaying = true;
function nextSlide() {
showSlide(currentSlide += 1)
}
function showSlide() {
var slides = document.getElementsByClassName("mySlides");
if (currentSlide > slides.length) {
currentSlide = 1;
}
for (i = 1; i < slides.length; i++) {
slides[i].style.opacity = "0";
}
slides[currentSlide-1].style.opacity = "1";
slides[currentSlide-1].style.transition = "all .5s";
// slides[slideIndex-1].setAttribute("style", "opacity: 1; transition: ease .5s;");
}
if (isPlaying) {
setTimeout(nextSlide, 1000);
}
</script>
I have modified your provided code a bit. Here is working example:
HTML
<div class="container">
<div class="mySlides" style="background-image: url('images/1.jpg')">1
</div>
<div class="mySlides" style="background-image: url('images/2.jpg');">2
</div>
<div class="mySlides" style="background-image: url('images/3.jpg');">3
</div>
Javascript:
var currentSlide = 1;
var isPlaying = true;
function nextSlide() {
showSlide(currentSlide += 1)
}
function showSlide() {
var slides = document.getElementsByClassName("mySlides");
if (currentSlide >= slides.length) {
currentSlide = 0;
}
for (i = 0; i < slides.length; i++) {
slides[i].style.opacity = "0";
slides[i].style.display = "none";
}
slides[currentSlide].style.display = "block";
slides[currentSlide].style.opacity = "1";
slides[currentSlide].style.transition = "all .5s";
// slides[slideIndex-1].setAttribute("style", "opacity: 1; transition: ease .5s;");
}
if (isPlaying) {
setInterval(nextSlide, 500);
}

Why won't my images fade in and out?

So I am currently working on a slideshow project in jQuery where images will fade in and out. The problem is that this only works on my KhanAcademy project, and not on my CodePen - Pen.
Can someone please tell me the issue on my CodePen? Thank you!
Code:
var slideShow = function(container, time, effect) {
container = document.querySelector(container);
this.images = [];
this.curImage = 0;
if (effect === "fade") {
for (i = 0; i < container.childElementCount; i++) {
this.images.push(container.children[i]);
this.images[i].style.opacity = 0;
}
// Handle going to to the next slide
var nextSlide = function() {
for (var i = 0; i < this.images.length; i++) {
if (i != this.curImage) this.images[i].style.opacity = 0;
}
this.images[this.curImage].style.opacity = 1;
this.curImage++;
if (this.curImage >= this.images.length) {
this.curImage = 0;
}
window.setTimeout(nextSlide.bind(document.getElementById(this)), time);
};
nextSlide.call(this);
} else if (effect === "clickFade") {
for (i = 0; i < container.childElementCount; i++) {
this.images.push(container.children[i]);
this.images[i].style.opacity = 0;
}
// Handle going to to the next slide
var nextSlideClick = function() {
for (var i = 0; i < this.images.length; i++) {
if (i != this.curImage) this.images[i].style.opacity = 0;
}
this.images[this.curImage].style.opacity = 1;
this.curImage++;
if (this.curImage >= this.images.length) {
this.curImage = 0;
}
window.setTimeout(nextSlideClick.bind(document.getElementById(this)), time);
};
nextSlideClick.call(this);
}
};
slideShow(".slideshow", 2000, "fade");
h1 {
font-family: 'Montserrat', sans-serif;
}
.slide {
transition: opacity 0.5 s;
position: absolute;
top: 1;
}
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<h1>Exatreo.js - Slideshow library</h1>
<div class="slideshow">
<img class="slide" src="https://www.kasandbox.org/programming-images/animals/birds_rainbow-lorakeets.png" alt="Rainbow lorakeets" />
<img class="slide" src="https://www.kasandbox.org/programming-images/animals/butterfly.png" alt="Butterfly" />
<img class="slide" src="https://www.kasandbox.org/programming-images/animals/cat.png" alt="Cat" />
<img class="slide" src="https://www.kasandbox.org/programming-images/animals/crocodiles.png" alt="Crocodiles" />
<img class="slide" src="https://www.kasandbox.org/programming-images/animals/fox.png" alt="Fox" />
</div>
If you will check your css with the validator you will get this error:
0.5 is not a transition value : opacity 0.5 s
And you can see that you have a space between the 0.5 and the s.
Remove this space and it will work as expected.
var slideShow = function(container, time, effect) {
container = document.querySelector(container);
this.images = [];
this.curImage = 0;
if (effect === "fade") {
for (i = 0; i < container.childElementCount; i++) {
this.images.push(container.children[i]);
this.images[i].style.opacity = 0;
}
// Handle going to to the next slide
var nextSlide = function() {
for (var i = 0; i < this.images.length; i++) {
if (i != this.curImage) this.images[i].style.opacity = 0;
}
this.images[this.curImage].style.opacity = 1;
this.curImage++;
if (this.curImage >= this.images.length) {
this.curImage = 0;
}
window.setTimeout(nextSlide.bind(document.getElementById(this)), time);
};
nextSlide.call(this);
} else if (effect === "clickFade") {
for (i = 0; i < container.childElementCount; i++) {
this.images.push(container.children[i]);
this.images[i].style.opacity = 0;
}
// Handle going to to the next slide
var nextSlideClick = function() {
for (var i = 0; i < this.images.length; i++) {
if (i != this.curImage) this.images[i].style.opacity = 0;
}
this.images[this.curImage].style.opacity = 1;
this.curImage++;
if (this.curImage >= this.images.length) {
this.curImage = 0;
}
window.setTimeout(nextSlideClick.bind(document.getElementById(this)), time);
};
nextSlideClick.call(this);
}
};
slideShow(".slideshow", 2000, "fade");
h1 {
font-family: 'Montserrat', sans-serif;
}
.slide {
transition: opacity 0.5s;
position: absolute;
top: 1;
}
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<h1>Exatreo.js - Slideshow library</h1>
<div class="slideshow">
<img class="slide" src="https://www.kasandbox.org/programming-images/animals/birds_rainbow-lorakeets.png" alt="Rainbow lorakeets" />
<img class="slide" src="https://www.kasandbox.org/programming-images/animals/butterfly.png" alt="Butterfly" />
<img class="slide" src="https://www.kasandbox.org/programming-images/animals/cat.png" alt="Cat" />
<img class="slide" src="https://www.kasandbox.org/programming-images/animals/crocodiles.png" alt="Crocodiles" />
<img class="slide" src="https://www.kasandbox.org/programming-images/animals/fox.png" alt="Fox" />
</div>

Categories