How can I change the image(slider) one by one every 3 seconds in javascript?
You better use Owl Carousel
self-coded sliders are not used in commercial development
But if we proceed with this, then here is the working example
I added 4 lines below:
var timer = setInterval(function(){
slideIndex++;
showSlides(slideIndex);
},3000);
It works, can't see any trouble
Did I understood what you needed?
How to change an image every 5 seconds for example?
you should run 'change' function outside of the func and pass the function name to the setInterval func as below
let images = ['photoFromInternet', 'photoFromInternet2', 'photoFromInternet3'];
let index = 0;
const imgElement = document.querySelector('#mainPhoto');
function change() {
imgElement.src = images[index];
index > 1 ? index = 0 : index++;
}
window.onload = function () {
setInterval(change, 5000);
};
How to make this carousel change the image every 'defined' seconds?
You can use this I think
$('.carousel').carousel({
interval: 1000 * 10
});
or
<div id="myCarousel" class="carousel slide" data-interval="1000" data-ride="carousel">
Making a image slider, that changes images every 6 seconds
This is not the edit of your posted fiddle.It is the fiddle that i created before and edited for this answer now.
Try this fiddle:
http://jsfiddle.net/kzQFQ/77/
var check=0;
var timer;
var Wwidth=$(window).width()-9;
$(document).ready(function () {
$('.contentContainer').css({'width':''+Wwidth+'px'});
$('.three').click(function () {
$('.container').animate({
'left': '-1120px'
});
clearTimeout(timer);
timer=setTimeout(function () {$('.one').click();}, 6000);
});
$('.two').click(function () {
$('.container').animate({
'left': '-560px'
});
clearTimeout(timer);
timer=setTimeout(function () {$('.three').click();}, 6000);
});
$('.one').click(function () {
$('.container').animate({
'left': ''+0+'px'
});
clearTimeout(timer);
timer=setTimeout(function () {$('.two').click();}, 6000);
});
timer=setTimeout(function () {$('.two').click();}, 6000);
});
Change images in a slide of an image slideshow
If you inspect the HTML code generated by JavaScript, you'll notice that Cycle2 duplicates the first slide and makes it invisible. The reason for this is beyond me, but at least we can easily work around it.
Secondly, you should trigger the fade-in/fade-out animation in cycle-after
. If this is done in cycle-before
, the setTimeout
counter begins while the slideshow is still transitioning to the next slide. Another problem is that in cycle-after
, optionHash.currSlide
is set to the previous slide...
In order to work around all those issues, we have to calculate the index of the currently visible slide like so:
var visibleSlide = ((optionHash.currSlide + 1) % optionHash.slideCount) + 1;
Regarding the broken previous/back buttons, it actually should be enough to completely stop the fade-in/fade-out animation and reset it when one of the buttons is clicked. However, when the prev button is clicked, the index calculation has to be adjusted (-1
instead of +1
, see code below).
Furthermore, we have to trigger the fade-in/fade-out animation "manually" for the very first slide right after initialization of the slideshow. To do this, we can use the cycle-initialized
event combined with the logic from cycle-after
.
I guess code says more than a thousand words, so here is my suggestion:
$(".slide img:nth-child(2)").hide();
// Workaround for first slide right after initialization
// Handler has to be set before initialization, otherwise it might never be called!
$("#slides").on("cycle-initialized", function(event, optionHash){
// Pretend the slideshow just transitioned from the last slide to the first
onCycleAfter(optionHash.slideCount-1, optionHash.slideCount);
});
$("#slides").cycle({
fx: "scrollHorz",
slides: ".slide",
timeout: 6000,
prev: "#prev",
next: "#next"
});
var timeout, prevClicked = false;
$("#slides").on("cycle-after", function(event, optionHash){
onCycleAfter(optionHash.currSlide, optionHash.slideCount);
});
$("#slides").on("cycle-prev", function(){
prevClicked = true;
});
function onCycleAfter(currSlide, slideCount) {
// Reset slides
$(".slide img:first-child").show();
$(".slide img:nth-child(2)").hide();
// Reset animation
clearTimeout(timeout);
$(".slide img").finish();
// Calculate current slide (with workaround for prev button)
var visibleSlide;
if (prevClicked) {
visibleSlide = ((currSlide - 1 + slideCount) % slideCount) + 1;
prevClicked = false;
}
else {
visibleSlide = ((currSlide + 1) % slideCount) + 1;
}
// Trigger new animation
timeout = setTimeout(function(){
var slideImages = $(".slide").eq(visibleSlide).find("img");
slideImages.eq(0).fadeOut(1000, function(){
slideImages.eq(1).fadeIn(1000);
});
}, 1000);
}
DEMO (JSFiddle)
Image in slider dissapear after few seconds
I try your code in fiddle and it's work fine :
Here is my fiddle http://jsfiddle.net/numa1x39/8/
var slideIndex = 1;showSlides(slideIndex);
// Next/previous controlsfunction plusSlides(n) { showSlides(slideIndex += n);}
// Thumbnail image controlsfunction currentSlide(n) { showSlides(slideIndex = n);}
function showSlides(n) { var i; var slides = document.getElementsByClassName("mySlides"); var dots = document.getElementsByClassName("dot"); if (n > slides.length) {slideIndex = 1} if (n < 1) {slideIndex = slides.length} for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } for (i = 0; i < dots.length; i++) { dots[i].className = dots[i].className.replace(" active", ""); } slides[slideIndex-1].style.display = "block"; dots[slideIndex-1].className += " active";}
* {box-sizing:border-box}
/* Slideshow container */.slideshow-container { max-width: 1000px; position: relative; margin: auto;}
/* Hide the images by default */.mySlides { display: none;}
/* Next & previous buttons */.prev, .next { cursor: pointer; position: absolute; top: 50%; width: auto; margin-top: -22px; padding: 16px; color: white; font-weight: bold; font-size: 18px; transition: 0.6s ease; border-radius: 0 3px 3px 0;}
/* Position the "next button" to the right */.next { right: 0; border-radius: 3px 0 0 3px;}
/* On hover, add a black background color with a little bit see-through */.prev:hover, .next:hover { background-color: rgba(0,0,0,0.8);}
/* Caption text */.text { color: #f2f2f2; font-size: 15px; padding: 8px 12px; position: absolute; bottom: 8px; width: 100%; text-align: center;}
/* Number text (1/3 etc) */.numbertext { color: #f2f2f2; font-size: 12px; padding: 8px 12px; position: absolute; top: 0;}
/* The dots/bullets/indicators */.dot { cursor: pointer; height: 15px; width: 15px; margin: 0 2px; background-color: #bbb; border-radius: 50%; display: inline-block; transition: background-color 0.6s ease;}
.active, .dot:hover { background-color: #717171;}
/* Fading animation */.fade { -webkit-animation-name: fade; -webkit-animation-duration: 1.5s; animation-name: fade; animation-duration: 1.5s;}
@-webkit-keyframes fade { from {opacity: .4} to {opacity: 1}}
@keyframes fade { from {opacity: .4} to {opacity: 1}}
.slider-img { width: 100%;}
<div class="slideshow-container"> <!-- Full-width images with number and caption text --> <div class="mySlides fade"> <div class="numbertext">1 / 3</div> <img src="https://static2.farakav.com/files/pictures/thumb/01125088.jpg" class="slider-img"> <div class="text">Caption Text</div> </div>
<div class="mySlides fade"> <div class="numbertext">2 / 3</div> <img src="https://static2.farakav.com/files/pictures/thumb/01324464.jpg" class="slider-img"> <div class="text">Caption Two</div> </div>
<div class="mySlides fade"> <div class="numbertext">3 / 3</div> <img src="https://static2.farakav.com/files/pictures/thumb/01324567.jpg" class="slider-img"> <div class="text">Caption Three</div> </div>
<!-- Next and previous buttons --> <a class="prev" onclick="plusSlides(-1)">❮</a> <a class="next" onclick="plusSlides(1)">❯</a> </div> <br>
<!-- The dots/circles --> <div style="text-align:center"> <span class="dot" onclick="currentSlide(1)"></span> <span class="dot" onclick="currentSlide(2)"></span> <span class="dot" onclick="currentSlide(3)"></span> </div> </div>
Image change every 30 seconds - loop
I agree with using frameworks for things like this, just because its easier. I hacked this up real quick, just fades an image out and then switches, also will not work in older versions of IE. But as you can see the code for the actual fade is much longer than the JQuery implementation posted by KARASZI István.
function changeImage() {
var img = document.getElementById("img");
img.src = images[x];
x++;
if(x >= images.length) {
x = 0;
}
fadeImg(img, 100, true);
setTimeout("changeImage()", 30000);
}
function fadeImg(el, val, fade) {
if(fade === true) {
val--;
} else {
val ++;
}
if(val > 0 && val < 100) {
el.style.opacity = val / 100;
setTimeout(function(){ fadeImg(el, val, fade); }, 10);
}
}
var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);
Changing src after 3 seconds
You should change src
one by one with interval time so don't use while || for
loops.
Try this example with setTimeout()
var $bg = $('.bg');
function bgChange(i) {
if(i == 6)i = 1; // reset
var background = '<?php echo $siteroot; ?>/img/bg' + i + '.jpg';
$bg.attr('src', background); // change src
setTimeout(function(){bgChange(i++)}, 3000); // call again after 3 sec
}
bgChange(1);
change/shift down class names on div for every 3 seconds on React
i was going to create a mobile responsive image slider like this without any npm packages or dependencies.
Follow these steps below and carefully refer the code below as well
create an object that can store tailwind classes(or css class names) for each of these images. i have created 7 styles because both first img from left and right side images are hidden in order to make a infinite slider.
at the top i defined a sliderIndex variable which has a initial value of 0, for every 3000 seconds we increase it value by 1 (that's same as pressing the next button for every 3000 seconds), using setInterval js function
when the sliderIndex value changes each image get different styles from the classes object, ( see this property on each image
${styleValues[(sliderIndex + 0) % styleValues.length]
) on first iteration it will be like 0,1,2,3,4,5,6 on next iteration it will start from 1,2,3,4,5,6,0 on the next it will be 2,3,4,5,6,1,2 so each images that get these classes place them self according to the styles which we gave using styles object.
That's all you have to do to make a slider without any packages, i used left,right css properties to move the images and then only figured out about transform property is more suitable for this task so you can use it if you want better performance.
import {BsArrowLeftCircle, BsArrowRightCircle} from 'react-icons/bs'
import { useEffect, useState } from "react
const ImageSlider = () => {
const [sliderIndex, setSliderIndex] = useState(0)
const classes = {
hideLeft: "opacity-0 -left-1/4 ",
first: "opacity-0 scale-100 | md:-left-1/4 | lg:left-0 lg:opacity-100",
prev: "-translate-x-full opacity-0 scale-100 | md:left-0 md:opacity-100 md:-translate-x-0 | lg:opacity-100 lg:left-1/3 lg:-translate-x-3/4 ",
selected: "z-20 left-0 md:scale-110 md:left-1/2 md:-translate-x-1/2",
next: "z-20 scale-100 left-full -translate-x-full | md:z-10 md:left-full md:-translate-x-full | lg:opacity-100 lg:left-2/3 lg:-translate-x-1/4",
last: "scale-100 left-full | lg:opacity-100 lg:-translate-x-full ",
hideRight:"opacity-0 left-full w-0"
}
const styleValues = Object.values(classes)
const handleNextClick = () => {
setSliderIndex((prev) => prev + 1)
}
const handlePreviousClick = () => {
setSliderIndex((prev) => prev - 1)
}
useEffect(() => {
const interval = setInterval(() => {
handleNextClick()
}, 3000)
return () => clearInterval(interval)
},[]
)
return (
<Section outerCustomClass="mb-20 mt-10">
<div className="flex flex-col items-center gap-y-4 ">
{/* images */}
<div className="w-full h-fit">
<div className="relative overflow-hidden w-full">
<div className={`absolute top-1/2 -translate-y-1/2 w-40 md:w-44 xl:w-48 2xl:w-72 ${styleValues[(sliderIndex + 0) % styleValues.length]} `}>
<img className="rounded h-96 w-80 object-contain" src="/images/common/slider/1.jpg" alt="" />
</div>
<div className={`absolute top-1/2 -translate-y-1/2 w-40 md:w-44 xl:w-48 2xl:w-72 ${styleValues[(sliderIndex + 1) % styleValues.length]} `}>
<img className="rounded h-96 w-80 object-contain" src="/images/common/slider/2.jpg" alt="" />
</div>
<div className={`absolute top-1/2 -translate-y-1/2 w-40 md:w-44 xl:w-48 2xl:w-72 ${styleValues[(sliderIndex + 2 ) % styleValues.length]}`}>
<img className="rounded h-96 w-80 object-contain" src="/images/common/slider/3.jpg" alt="" />
</div>
<div className={`absolute top-1/2 -translate-y-1/2 w-40 md:w-44 xl:w-48 2xl:w-72 ${styleValues[(sliderIndex + 3) % styleValues.length]}`}>
<img className="rounded h-96 w-80 object-contain" src="/images/common/slider/4.jpg" alt="" />
</div>
<div className={`absolute top-1/2 -translate-y-1/2 w-40 md:w-44 xl:w-48 2xl:w-72 ${styleValues[(sliderIndex + 4) % styleValues.length]}`}>
<img className="rounded h-96 w-80 object-contain" src="/images/common/slider/5.jpg" alt="" />
</div>
<div className={`absolute top-1/2 -translate-y-1/2 w-40 md:w-44 xl:w-48 2xl:w-72 ${styleValues[(sliderIndex + 5) % styleValues.length]}`}>
<img className="rounded h-96 w-80 object-contain" src="/images/common/slider/6.jpg" alt="" />
</div>
<div className={`absolute top-1/2 -translate-y-1/2 w-40 md:w-44 xl:w-48 2xl:w-72 ${styleValues[(sliderIndex + 6) % styleValues.length]} `}>
<img className="rounded h-96 w-80 object-contain" src="/images/common/slider/7.jpg" alt="" />
</div>
</div>
</div>
<div className="text-sea-base flex gap-x-4 w-20 md:w-40 cursor-pointer">
<BsArrowLeftCircle size={50} onClick={handlePreviousClick} />
<BsArrowRightCircle size={50} onClick={handleNextClick} />
</div>
Related Topics
Pdf Blob - Pop Up Window Not Showing Content
Expected Linebreaks to Be 'Lf' But Found 'Crlf' Linebreak-Style
How to Resolve the C:\Fakepath
Different Color for Each Bar in a Bar Chart; Chartjs
Concatenating Variables and Strings in React
How to Pass Event as Argument to an Inline Event Handler in JavaScript
How to Wait Until All JavaScript Files Are Loaded Before Executing JavaScript Code
Angularjs Directive Does Not Update on Scope Variable Changes
How to Get Convert an Object to HTML Markup
Trigger JavaScript Event If Div Innertext Change
Jquery Datatables: Hide Search Bar
Displaying Navbar on Multiple HTML Pages Using Bootstrap
Split String in JavaScript and Detect Line Break
Change Value of a Variable Inside Foreach Loop? Make It Available Outside the Loop
How to Pass Data from Flask to JavaScript in a Template
How to Modify Chartjs Tooltip So I Can Add Customized Strings in Tooltips
Cannot Read Property of Undefined @Viewchild Not Working Angular 5
React Native How to Call Multiple Functions When Onpress Is Clicked