show images one by one using fadein and fadeout in jquery - javascript

Today while creating a slider i stuck in the middle of code that how can i fadein and fadeout the image one by one in jquery. Code i tried so far:-
<head>
<style>
#slideshow{
list-style: none;
width: 100%;
height: 100%;
top: 0;
left: 0;
padding: 0;
margin: 0;
position:fixed;
}
ul{
list-style-type:none;
}
ul li{
display:inline;
width: 100%;
height: 100%;
position:absolute;
background-size:cover;
background-position:center center;
}
ul li img{
display:none;
}
</style>
</head>
<body>
<ul id="slideshow">
<li><img src="img/1.jpg" /></li>
<li><img src="img/2.jpg" /></li>
<li><img src="img/3.jpg" /></li>
</ul>
<script>
window.onload=init;
function init(){
items=$('ul').children('li');
i=0;
item=$(items[i]);
item.css('background-image','url('+ item.find('img').attr('src') +')').fadeOut(1000,function(){
for(i=0;i<items.length;i++){
item=$(items[i]);
item.css('background-image','url('+ item.find('img').attr('src') +')');
}
});
}
</script>
</body>
After showing first image it automatically goes to last image without displaying the second image.
Please help me to rectify this problem.

Here's how you can do it: JSFiddle
function init(){
$("#slideshow li").each(function(index){
this.style.backgroundImage = "url('" + this.children[0].src + "')";
if( index != 0)
this.style.display = "none";
});
setTimeout(changeImage, 4000);
}
function changeImage(){
$curr = $("#slideshow .active");
$next = $("#slideshow .active").next();
if($next[0] === undefined)
$next = $("#slideshow li").eq(0);
$curr.fadeOut(1000, function(){
$next.fadeIn(1000, function(){
$curr.removeClass("active");
$next.addClass("active");
setTimeout(changeImage, 4000); //change image every 4 seconds
});
});
}
$(document).ready(init);

You need to use the setInterval() and something must tell you what is the current img. Assume that all image is hidden exept for the active one.
<ul id="slideshow">
<li class="active"><img src="img/1.jpg" /></li>
<li><img src="img/2.jpg" /></li>
<li><img src="img/3.jpg" /></li>
</ul>
function ShowNext()
{
var current = $("#slideshow .active");
$(current).removeClass("active");
$(current).fadeOut(1000, function () {
$(current).next().fadeIn(1000);
$(current).next().addClass("active");
});
}
setInterval(function() {
ShowNext();
}, 4000);
Code not tested but this is how you should do it. Also you need to do something when you reach the end of the slider but i'm sure you can handle that.

I'd suggest having a single element instead of 3.
Also, use a recursive function to swap the image every 2 seconds.
Lastly note the javascript has been moved inside the <head> element where it should be.
Update: This has been tested and works great - had to fix a few bugs - here's the updated code:
<html>
<head>
<style><!-- Your Styles --></style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script language="javascript">
var imgNum = 1;
$(document).ready(function() {
doSlideshow();
});
function doSlideshow() {
$('#image1').fadeOut(400, function() {
$('#image1').attr('src', 'img/' + imgNum + '.jpg');
$('#image1').fadeIn(400);
imgNum++;
if (imgNum == 4) { imgNum = 1; }
setTimeout('doSlideshow()', 2000);
});
}
</script>
</head>
<body>
<ul id="slideshow">
<li><img id="image1" src="" /></li>
</ul>
</body>
</html>

There are definitely more than one way to do this.
I answered a similar question here:
>> Adding fade to simple slideshow with Javascript <<
However, to answer YOUR question directly, consider the following:
>> WORKING JS FIDDLE <<
// create arbitrary namespace
window.slideshow = {
slides: null,
currentSlide: null,
nextSlide: null,
interval: 3000,
timer: null,
init: function() {
console.log('init slideshow');
this.slides = $('#slideshow img');
this.planNextSlide(1);
},
planNextSlide: function(timeoutInterval) {
console.log('next slide (' + timeoutInterval + ')');
this.timer = setTimeout(this.transitionSlide, timeoutInterval);
},
transitionSlide: function() {
console.log('transition slide (' + (slideshow.currentSlide != null) + ')');
if (slideshow.currentSlide != null) {
// fade out old slide first
slideshow.slides.eq(slideshow.currentSlide).fadeOut('fast', function() {
slideshow.nextSlide = slideshow.currentSlide + 1;
if (slideshow.nextSlide == slideshow.slides.size()) {
slideshow.nextSlide = 0;
}
slideshow.currentSlide = null;
slideshow.transitionSlide();
});
}
else {
// fade in new slide
slideshow.nextSlide = slideshow.nextSlide == null ? 0 : slideshow.nextSlide;
slideshow.slides.eq(slideshow.nextSlide).fadeIn('fast', function() {
slideshow.currentSlide = slideshow.nextSlide;
slideshow.planNextSlide(slideshow.interval);
});
}
}
};
// initial state initializer
slideshow.init();

Related

JavaScript - periodically change "active" image

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.

Slideshow wont restart

I am trying to create a slideshow for my website but i have no idea
how to make the array restart. I tried putting a for loop in the function but the page only shows the last image every time it reloads. here is the code:
var i=0;
function myfunc(){
console.log(i);
slideShowImage.src = images[i];
console.log(slideShowImage.src);
/**
if (images[i] =="Mir.jpg"){
link = document.getElementById("slideShowLink");
link.href="http://stackoverflow.com";
}
*/
i = i+1;
}
setInterval(myfunc,5000);
Sounds like you want i to wrap back around to 0 after it hits the last image in images. Try replacing i with i % images.length like so:
var i=0;
function myfunc(){
console.log(i);
slideShowImage.src = images[i % images.length];
console.log(slideShowImage.src);
/**
if (images[i] =="Mir.jpg"){
link = document.getElementById("slideShowLink");
link.href="http://stackoverflow.com";
}
*/
i = i+1;
}
setInterval(myfunc,5000);
I think you are missing a component to your function. I think you need to add to your function:
var $next = $active.next().length ? $active.next()
: $('#slideshow IMG:first');
Here is code that I have used to make my own slideshow:
function slideSwitch() {
var $active = $('#slideshow IMG.active');
if ( $active.length == 0 ) $active = $('#slideshow IMG:last');
var $next = $active.next().length ? $active.next()
: $('#slideshow IMG:first');
$active.addClass('last-active');
$next.css({opacity: 0.0})
.addClass('active')
.animate({opacity: 1.0}, 1000, function() {
$active.removeClass('active last-active');
});
}
$(function() {
setInterval( "slideSwitch()", 5000 );
});
The function tells it where to start and that at the end, it needs to go back to the first. This is then incorporated in the setInternal at the end.
Here is the css if you want it:
#slideshow {
position:relative;
height:350px;
}
#slideshow IMG {
position:absolute;
top:0;
left:0;
z-index:8;
}
#slideshow IMG.active {
z-index:10;
}
#slideshow IMG.last-active {
z-index:9;
}
And the html:
<div id="slideshow">
<img src="img/img1.jpg" alt="" class="active" />
<img src="img/img2.jpg" alt="" />
<img src="img/img3.jpg" alt="" />
</div>

Change image every 10 second

I want to change image every 10 seconds in javascript, can someone help me?
Here's the images, I only want add some code on javascript without changing these code below
HTML
<body onload = "imageChanger()">
<div>
<ul>
<li><img src = "images/img1.jpg"/></li>
<li><img src = "images/img2.jpg"/></li>
<li><img src = "images/img3.jpg"/></li>
<li><img src = "images/img4.jpg"/></li>
</ul>
</div>
</body>
CSS
div {margin: 50px auto; height: 500px; width: 800px; overflow: hidden; border: 10px solid;}
img {width: 800px; height: 500px;}
ul {list-style-type: none; padding: 0; margin: 0;}
I want to add some code that will change image on load:
JS
function imageChanger()
{
//Code here
}
Here is what I did for a similar scenario.
<body id="background">
<script>
$(function () {
var imageArray = ['BG-1.jpg', 'BG-2.jpg', 'BG-3.jpg', 'BG-4.jpg', 'BG-5.jpg', 'BG-6.jpg', 'BG-7.jpg', 'BG-8.jpg', 'BG-9.jpg', 'BG-10.jpg', 'BG-11.jpg', 'BG-12.jpg', 'BG-13.jpg', 'BG-14.jpg', 'BG-15.jpg', 'BG-16.jpg', 'BG-17.jpg', 'BG-18.jpg', 'BG-19.jpg', 'BG-20.jpg', 'BG-21.jpg', 'BG-22.jpg']
// on page load
$('#background').css({ 'background-image': 'url(/Content/img/BackGround/' + imageArray[Math.floor(Math.random() * imageArray.length)] + ')', 'background-size': 'cover' })
// every 10 seconds change to random image name in the array
setInterval(function () {
$('#background').css({ 'background-image': 'url(/Content/img/BackGround/' + imageArray[Math.floor(Math.random() * imageArray.length)] + ')', 'background-size': 'cover' })
}, 10000);
});
</script>
</body>
You can use setInterval() for this.
Code
var i = 0;
setInterval(changeImage, 10000);
changeImage(); //Initial call to hide the images on start
function changeImage() {
i = (i + 1) % $('li').length; //Make sure the list wraps back to 0
$('li:eq(' + i + ')').show().siblings().hide();
}
Fiddle

Improve slide effect

I have created a simple slider
html
<div id="sldvid1" class="slider" >
<img picnum="1" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail1.png" />
<img picnum="2" style="display:none;" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail7.png" />
<img picnum="3" style="display:none;" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail14.png" />
</div>
<hr>
<div id="sldvid2" class="slider" >
<img picnum="1" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail1.png" />
<img picnum="2" style="display:none;" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail7.png" />
<img picnum="3" style="display:none;" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail14.png" />
</div>
$
var timer1 = setInterval(runSlide, 1000);
var curnum = 1;
function runSlide()
{
curnum = $(".slider img:visible").attr('picnum');
//$("#sldvid1 img[picnum=" + curnum + "]").fadeOut();
if(curnum == 3){
curnum = 1;
}
else
{
curnum++;
}
// $(".slider img").hide();
//$(".slider img[picnum=" + curnum + "]").show();
$(".slider img").hide();
$(".slider img[picnum=" + curnum + "]").show();
//console.log(curnum);
}
CSS
.slider{
height:50px;
}
Demo
http://jsfiddle.net/mparvez1986/vf401e2y/
Everything is working fine, I just need some one to improve effect so that it could effect like moving from left to right, I tried with some effect, but it seems it required some css manipulation as well
Thanks
I modified your code to create a carousel where images are slid in and out. I accomplished this by animating the margin-left CSS property with jQuery. I specified a size for the .slider class and used overflow: hidden; to ensure the sliding images were not displayed outside of it.
If you wish, you can change the transition effect by changing the CSS property that is animated and ensuring that the elements are in the correct position for the animation before it begins.
You can also change the speed of the animation by changing the magic number 1000 that I've left in the calls to animate. This number is specified in milliseconds.
By the way, I should point out that while custom HTML attributes are allowed in HTML5 they should begin with data-; they are called data attributes.
jsfiddle
HTML
<div id="sldvid1" class="slider">
<img class="active" data-slide-to="0" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail1.png"/>
<img data-slide-to="1" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail7.png"/>
<img data-slide-to="2" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail14.png"/>
</div>
<hr>
<div id="sldvid2" class="slider">
<img class="active" data-slide-to="0" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail1.png"/>
<img data-slide-to="1" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail7.png"/>
<img data-slide-to="2" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail14.png"/>
</div>
CSS
.slider {
position: relative;
width: 50px;
height: 50px;
overflow: hidden;
}
.slider img {
display: none;
width: 100%;
position: absolute;
}
.slider .active {
display: inline-block;
}
.slider .sliding {
display: inline-block;
}
JavaScript
var timer = setInterval(runSlide, 2000);
function runSlide() {
// Slide each slider on the page.
$(".slider").each(function (index, element) {
// Get the elements involved in the slide.
var numChildren = $(this).children().length;
var activeChild = $(this).children(".active");
var activeSlideTo = $(activeChild).attr("data-slide-to");
var nextSlideTo = (parseInt(activeSlideTo) + 1) % numChildren;
var nextChild = $(this).find("*[data-slide-to=" + nextSlideTo + "]");
// Prepare for slide.
$(activeChild).css("margin-left", "0%");
$(nextChild).css("margin-left", "-100%");
$(activeChild).addClass("sliding");
$(nextChild).addClass("sliding");
$(activeChild).removeClass("active");
// Slide using CSS margin-left.
$(activeChild).animate({"margin-left": "100%"}, 1000, function () {
$(this).removeClass("sliding");
});
$(nextChild).animate({"margin-left": "0%"}, 1000, function () {
$(this).addClass("active");
$(this).removeClass("sliding");
});
});
}
Ended with following
setInterval(function() {
$('#sldvid1 > img:first')
.fadeOut(1000)
.next()
.fadeIn(1000)
.end()
.appendTo('#sldvid1');
}, 3000);

How to get a jquery rotator to fade from one image to the next?

I am using jquery to create an image rotator. I found the code below here: How to fade loop gallery background images
but I was wondering if there is a way it can fade from one image to the next instead of to white in between?
$(window).load(function(){
var initialBg = $('#mydiv').css("background-image"); // added
var firstTime = true;
var arr = [initialBg, "url(HP_jQuery2.jpg)", "url(HP_jQuery3.jpg)"]; // changed
(function recurse(counter) {
var bgImage = arr[counter];
if (firstTime == false) {
$("#mydiv").fadeOut("slow", function(){
$('#mydiv').css('background-image', bgImage); // fixed
});
$("#mydiv").fadeIn("slow");
} else {
firstTime = false;
}
delete arr[counter];
arr.push(bgImage);
setTimeout(function() {
recurse(counter + 1);
}, 3600);
})(0);
});
Give this a try: http://www.simonbattersby.com/blog/simple-jquery-image-crossfade/
JSFiddle demo
HTML:
<div id="cycler">
<img class="active" src="image1.jpg" alt="My image" />
<img src="image2.jpg" alt="My image" />
<img src="image3.jpg" alt="My image" />
<img src="image4.jpg" alt="My image" />
</div>
CSS:
#cycler { position:relative; }
#cycler img { position:absolute; z-index:1 }
#cycler img.active { z-index:3 }
JavaScript:
function cycleImages() {
var $active = $('#cycler .active');
var $next = ($active.next().length > 0) ? $active.next() : $('#cycler img:first');
$next.css('z-index', 2); //move the next image up the pile
$active.fadeOut(1500, function() { //fade out the top image
$active.css('z-index', 1).show().removeClass('active'); //reset the z-index and unhide the image
$next.css('z-index', 3).addClass('active'); //make the next image the top one
});
}
$(document).ready(function() {
// run every 3s
setInterval(cycleImages, 3000);
});

Categories