I have the following javascript. It works well when I am cycling between 2 images, but when I add a third it does not work correctly.
Here is my CSS:
img {
-webkit-transition-property: opacity;
-webkit-transition-duration: 2s;
position: absolute;
width: 320px;
height: auto;
}
img.fade-out {
opacity: 0;
}
img.fade-in {
opacity: 1;
}
Here is my javascript, which seems to work but seems laggy and definately not an elegant solution.
</head><body style="color: black">
<img id="one" class="fade-out" src="Wallpaper.png"/>
<img id="two" class="fade-out" src="Wallpaper0.png"/>
<img id="three" class="fade-out" src="Wallpaper1.png"/>
<script>
var images = ['Wallpaper.png', 'Wallpaper0.png', 'Wallpaper1.png'];
var index = 0;
var fade_in = one;
var fade_out = two;
var fade_foo = three;
fade_in.src = images[0];
fade_out.src = images[images.length - 1];
var fade = function () {
fade_in.src = images[index];
index = (index + 1) % images.length;
fade_in.className = 'fade-out';
fade_out.className = 'fade-in';
fade_foo.className = 'fade-out';
var fade_tmp = fade_in;
fade_in = fade_out;
fade_out = fade_foo;
fade_foo = fade_tmp;
setTimeout(fade, 15000);
};
fade();
</body></html>
For one thing, you're not changing fade_out.src. Try something like this:
fade_in.src = images[0];
fade_out.src = images[1]; // let's use image next to current for fade-out
var fade = function () {
fade_in.src = images[index];
index = (index + 1) % images.length;
fade_out.src = images[index]; // put next to current image into fade-out
// Code below does something misterious.
// You first switch classes between two img's, then switch variables themselves
// Why?
//fade_in.className = 'fade-out';
//fade_out.className = 'fade-in';
//var fade_tmp = fade_in;
//fade_in = fade_out;
//fade_out = fade_tmp;
setTimeout(fade, 15000);
};
Can't tell more since I don't know what exactly you're doing.
It seems you're only displaying one image at a time, so you don't need two variables, one will do. You just need to fade out the current image and bring in a new image:
var index = -1, count = /* total number of images */;
var image = null;
function fade() {
if (image != null)
image.className = 'fade-out';
index = (index + 1) % count;
image = document.getElementById('image-' + index);
image.className = 'fade-in';
setTimeout(fade, 15000);
}
fade();
This assumes that you have set up all the images in HTML as follows:
<img id="image-0" class="fade-out" src="..." />
<img id="image-1" class="fade-out" src="..." />
<img id="image-2" class="fade-out" src="..." />
...
Note that you can achieve cross-fading only if you have several images preloaded, as in the above example. If you use only one image and change the source, the previous image will be lost when you try to fade in the new one.
you're not waiting for you transitions to finish before you swap the source. we just need to rearrange the order of things.
var fade = function() {
fade_in.className = 'fade-out';
fade_out.className = 'fade-in';
setTimeout(function() {
index = (index + 1) % images.length;
fade_in.src = images[index]; // should be completely invisible at this time
var fade_tmp = fade_in;
fade_in = fade_out;
fade_out = fade_tmp;
}, 2000); // 2 seconds, same as your transition time
setTimeout(fade, 15000);
};
setTimeout(fade, 15000);
here the only work that the fade method does is to change the classes, which initiates the transitions. we set a delay that matches your transition time to update the index and swap the image source.
edits: i guess i'm not making it clear what's going on and the assumptions i'm making. here's my complete html except for the provided css which is the same. i also fixed an issue with image order since the last example.
<body>
<img id="one" class="fade-out" /><img id="two" class="fade-out" />
<script>
var images = ['16jog8h.jpg', '20_11_2007_0044537001195507712_joe_baran.jpg', '400davesrig.jpg'];
var index = 0;
var fade_in = document.getElementById('one');
var fade_out = document.getElementById('two');
// fade_in.src = images[0];
fade_out.src = images[0];
var fade = function() {
fade_in.className = 'fade-out';
fade_out.className = 'fade-in';
setTimeout(function() {
index = (index + 1) % images.length;
fade_in.src = images[index];
var fade_tmp = fade_in;
fade_in = fade_out;
fade_out = fade_tmp;
}, 2000);
setTimeout(fade, 5000);
};
fade();
</script>
</body>
Related
var n=0;
var images=["FullSizeRender (1).jpg","IMG_1875.JPG","IMG_4665.JPG","IMG_5213.JPG"];
$(document).ready(function() {
// Change image
$("#himg").click(function(){
n++;
if(n==images.length){
n=0;
};
document.getElementById("himg").src=images[n];
$("#himg").find('img[src="' + images[n] + '"]').fadeOut();
$("#himg").find('img[src="' + images[n+1] + '"]').hide().fadeIn();
});
<div class="col-xs-2">
<div id="handbags">
<h4>Handbags</h4>
<img id="himg" src="FullSizeRender (1).jpg" />
</div>
</div>
I have made an array where images change on click, but I am trying to make the images fade on click instead of sharply changing. I've tried selecting the images by source using the index from the array, but it's not working.
Try this:
$(document).ready(function() {
var n = 0;
var images = ["FullSizeRender(1).jpg","IMG_1875.JPG","IMG_4665.JPG","IMG_5213.JPG"];
var image = $('#himg');
image.on('click', function() {
var newN = n+1;
if (newN >= images.length) { newN = 0 };
image.attr('src', images[n]);
image.fadeOut(300, function () {
image.attr('src', images[newN]);
image.fadeIn();
n = newN;
});
});
});
I'm currently working on an image rotator. The rotation part is complete, however I'm expanding the functionality based on a need that I've found.
Goal: Rotate through a preset list of slides that contain hardcoded images, however on each subsequent rotation, use js to swap to a new image for specific slides that require a variation.
The script below works fine, but I feel like it's not the most efficient way to go about this. Currently I'm tackling it by running a new loop and function for each of the specific slides that I've chosen to be the "different" ones. My guess is there is a way to do it using one function and loop, but I'm not quite sure how to go about it.
Anology: Let's say I have an image rotator that displays a list of cars and every 5 seconds it rotates to the next slide. Each slide is designated for a different model of car, however for some models, I want to display a different variation of that model on each iteration of the entire rotator.
Example:
Here is a list of how each pass of the rotator would print.
- Ford Focus
- Toyota Celica
- Hyundai Elantra
- Dodge Ram
- Motorcycle
- Ford Focus
- Toyota Celica GTS
- Hyundai Elantra
- Dodge Ram w/ additional accessories
- Motorcycle
- Ford Focus
- Toyota Celica w/ Spoiler
- Hyundai Elantra
- Dodge Ram different color
- Motorcycle
Here is my current script:
<script>
window.onload=function() {
imgCont = document.getElementById('example1');
c_imgCont = document.getElementById('example2');
}
var myIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("slide");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1;
if (typeof(imgCont) != 'undefined' && imgCont != null)
{
swapImage();
}
if (typeof(c_imgCont) != 'undefined' && c_imgCont != null)
{
swapImageExample2();
}
}
x[myIndex-1].style.display = "block";
setTimeout(carousel, x[myIndex-1].dataset.timing);
}
var picPaths = ['image1.png','img2.png','img3.png','img4.png'];
var curPic = -1;
//preload the images for smooth animation
var imgO = new Array();
for(i=0; i < picPaths.length; i++) {
imgO[i] = new Image();
imgO[i].src = picPaths[i];
}
function swapImage() {
curPic = (++curPic > picPaths.length-1)? 0 : curPic;
imgCont.src = imgO[curPic].src;
}
var c_picPaths = ['otherimg1.png','otherimg2.png'];
var c_curPic = -1;
//preload the images for smooth animation
var c_imgO = new Array();
for(l=0; l < c_picPaths.length; l++) {
c_imgO[l] = new Image();
c_imgO[l].src = c_picPaths[l];
}
function swapImageExample2() {
c_curPic = (++c_curPic > c_picPaths.length-1)? 0 : c_curPic;
c_imgCont.src = c_imgO[c_curPic].src;
}
</script>
Why not just adjust your data structure so that any "image" in the picPaths array can be an array of image paths. Then use a function to get the image path to show. See simple example below.
Notice the structure of picPaths. Also notice that the 2nd and 4th images in the rotation (transport, nature) rotate through different images each iteration of the picPaths array.
<img id="example1" src="http://lorempixel.com/400/200/cats/1/"/>
<script>
window.onload = function() {
imgCont = document.getElementById('example1');
swapImage();
}
var picPaths = [
"http://lorempixel.com/400/200/cats/1/",
[
"http://lorempixel.com/400/200/transport/1/",
"http://lorempixel.com/400/200/transport/2/",
"http://lorempixel.com/400/200/transport/3/",
"http://lorempixel.com/400/200/transport/4/"
],
"http://lorempixel.com/400/200/animals/1/",
[
"http://lorempixel.com/400/200/nature/1/",
"http://lorempixel.com/400/200/nature/2/",
"http://lorempixel.com/400/200/nature/3/",
"http://lorempixel.com/400/200/nature/4/",
"http://lorempixel.com/400/200/nature/5/"
],
"http://lorempixel.com/400/200/sports/1/"
],
curImg = 0;
function getImagePath(path) {
if(Array.isArray(path)) {
var temp = path.shift();
path.push(temp);
return temp;
}
else {
return path;
}
}
function swapImage() {
curImg = curImg < (picPaths.length - 1) ? curImg : 0;
var imgPath = getImagePath(picPaths[curImg]);
console.clear();
console.log('current index in picPaths:', curImg, 'current image path to display:', imgPath);
imgCont.src = imgPath;
curImg++;
setTimeout(function() {
swapImage();
}, 4000);
}
</script>
Based on your comment I made a 2nd example. I think this is what you mean.
window.onload = function() {
carousel(picPaths, 'slide');
};
var picPaths = [
"https://placeimg.com/640/480/any/sepia/1",
[
"https://placeimg.com/640/480/tech/1",
"https://placeimg.com/640/480/tech/2",
"https://placeimg.com/640/480/tech/3",
"https://placeimg.com/640/480/tech/4"
],
"https://placeimg.com/640/480/animals/1",
[
"https://placeimg.com/640/480/nature/1",
"https://placeimg.com/640/480/nature/2",
"https://placeimg.com/640/480/nature/3",
"https://placeimg.com/640/480/nature/4",
"https://placeimg.com/640/480/nature/5"
],
"https://placeimg.com/640/480/arch/1"
];
function carousel(imgPaths, imgClass) {
var imgs = document.getElementsByClassName(imgClass);
Array.prototype.forEach.call(imgs, function(imgElem, idx) {
var timing = imgElem.dataset.timing,
path = imgPaths[idx];
swapImage(imgElem, path, timing);
});
function getImagePath(path) {
if(Array.isArray(path)) {
var temp = path.shift();
path.push(temp);
return temp;
}
else {
return path;
}
};
function swapImage(imgElem, path, timing) {
var imgPath = getImagePath(path);
imgElem.src = imgPath;
setTimeout(function() {
swapImage(imgElem, path, timing);
}, timing);
};
}
.slide {
width: 100px;
}
<div id="container">
<img id="slide_1" class="slide" src="" data-timing="8000">
<img id="slide_2" class="slide" src="" data-timing="4000">
<img id="slide_3" class="slide" src="" data-timing="10000">
<img id="slide_3" class="slide" src="" data-timing="6000">
</div>
I have to make a program which is able to present an animation once opened.
Here the code that I have so far, but I am not sure how to fix it to automatically show the pictures and I am not allowed to use a button or hover over the image to change it , and I'm not allowed to use a premade gif or a gif at all
var index = 0;
var ImageList = ["http://www.iconsplace.com/icons/preview/orange/happy-256.png", "http://www.iconsplace.com/icons/preview/orange/sad-256.png"];
var image1 = document.getElementById("myImage");
function onTimer() {
timerValue++;
para.innerHTML = timerValue;
if (timerValue >= 30) {
img.src("http://www.iconsplace.com/icons/preview/orange/happy-256.png");
} else if (timer <= 60) {
img.src("http://www.iconsplace.com/icons/preview/orange/sad-256.png");
} else {
img.src("http://www.iconsplace.com/icons/preview/orange/happy-256.png");
}
}
<img id="myImage" src="http://www.iconsplace.com/icons/preview/orange/happy-256.png" style="width:200px">
You can use an interval:
window.onload = function(){
var index = 0;
var ImageList = ["Images/happy.png", "Images/sad.png"];
var image1 = document.getElementById("myImage");
var a = 0;
setInterval(function(){
a++;
image1.src = ImageList[a % ImageList.length];
}, 30000);
}
It changes the image per 30 seconds.
You have the two images in an array. USE it!
var index = 0;
var ImageList = ["http://www.iconsplace.com/icons/preview/orange/happy-256.png", "http://www.iconsplace.com/icons/preview/orange/sad-256.png"];
window.onload=function() { // page has finished loading, image is available
var image1 = document.getElementById("myImage");
var tId=setInterval(function() {
index=index==0?1:0; // if 0 then 1 else 0
// for more images instead use:
// index++; if (index>=ImageList.length)index=0;
image1.src=ImageList[index]; // how to set the image src
},5000); // every 5 seconds
}
<img id="myImage" src="http://www.iconsplace.com/icons/preview/orange/happy-256.png" style="width:200px">
i have image gallery ant i set up setinterval, now i want that it should be stopped after two or tree circle.
This is my html Code:
<div id="slider">
<img src="http://imgsrc.hubblesite.org/hu/gallery/db/spacecraft/24/formats/24_web.jpg">
<img src="http://imgsrc.hubblesite.org/hu/gallery/db/spacecraft/27/formats/27_web.jpg">
<img src="http://imgsrc.hubblesite.org/hu/gallery/db/spacecraft/32/formats/32_web.jpg">
<img src="http://imgsrc.hubblesite.org/hu/gallery/db/spacecraft/33/formats/33_web.jpg">
</div>
css:
#slider {
width: 400px;
height: 300px;
position: relative;
overflow: hidden
}
#slider img {
position: absolute;
top: 0;
left: 0;
opacity: 0;
transition: 0.25s
}
and Javascript:
var pics;
var current = 0; // first next() moves to pics[0], the first image
window.addEventListener("load", function() {
pics = document.querySelectorAll("#slider img");
});
setInterval(function() {
var nextImage = (current + 1) % pics.length;
pics[current].style.opacity = 0;
pics[nextImage].style.opacity = 1;
current = nextImage;
}, 3000);
Here's your answer: Stop setInterval call in JavaScript
Save the interval ID when you create it, keep track of the number of times your slides have rotated, and then cancel the interval.
Use a counter variable to track the number of cycles & clear the timer based on that limit value.
JS Code:
var counter = 0;
var limit = 3 ;
var timer;
timer =setInterval(function () {
if(counter === 3){
clearInterval(timer);
return;
}
counter++;
//do some stuff here after 1 second delay
},1000);
You could use setTimeout instead.
var pics;
var current = 0; // first next() moves to pics[0], the first image
var stop = 3; //define when you want to stop
window.addEventListener("load", function() {
pics = document.querySelectorAll("#slider img");
});
function switchImage()
{
var nextImage = (current + 1) % pics.length;
pics[current].style.opacity = 0;
pics[nextImage].style.opacity = 1;
current = nextImage;
stop--;
if(stop != 0)
setTimeout(switchImage,3000);
}
setTimeout(switchImage,3000);
You can do like this.
var refreshIntervalId = setInterval(function() {
var nextImage = (current + 1) % pics.length;
pics[current].style.opacity = 0;
pics[nextImage].style.opacity = 1;
current = nextImage;
}, 3000);
clearInterval(refreshIntervalId);
I have following 4 bulbs:
<div id="bulb1" class="lightbulb"><img src=".\images\bulb.png" /></div>
<div id="bulb2" class="lightbulb"><img src=".\images\bulb.png" /></div>
<div id="bulb3" class="lightbulb"><img src=".\images\bulb.png" /></div>
<div id="bulb4" class="lightbulb"><img src=".\images\bulb.png" /></div>
My requirement is somewhat strange, but yes I have to do it...I have to do this in javascript.
I have an array which has 4 elements {1, 2, 3, 4}. Initially all bulbs(images) will be invisible.
First, I have to select on element from this array randomly. Suppose 2 is selected, then 2nd bulb will lighten up.
Then after 500 milliseconds, again my random function generator picks 4, then 4th bulb image is shown and 2nd is again invisible.
This I have to do 4 times in such a way that each time unique bulb gets lighten up. What approach and structure should I follow?
I am fused all the bulbs at beginning by calling this function
function hideBulbImages()
{
document.getElementById('bulb1').style.visibility = "hidden";
document.getElementById('bulb2').style.visibility = "hidden";
document.getElementById('bulb3').style.visibility = "hidden";
document.getElementById('bulb4').style.visibility = "hidden";
}
I am thinking of the function showBulbImage...
I have written showBulbImage to show the bulb sequentially after every second like this
function showBulbImages()
{
var blink_count = 0;
var blink_the_bulbs = setInterval(function() {
blink_count+=1;
hideBulbImages();
var blinking_bulb = "bulb" + blink_count;
document.getElementById(blinking_bulb).style.visibility = "visible";
if (blink_count > 4)
{
clearInterval(blink_the_bulbs);
}
}, 1000);
}
Now I have to randomize the visibility of bulbs.
Use setInterval() and Math.random()
function get_random_bulb() gets a random number, hides visible image first and then shows random image.
js:
$(document).ready(function () {
get_random_bulb();
function get_random_bulb() {
var a = (parseInt(Math.random() * 4));
$(".lightbulb img.block").removeClass("block").addClass("none");
$(".lightbulb:eq(" + a + ") img").removeClass("none").addClass("block");
}
setInterval(function () {
get_random_bulb();
}, 500);
});
<div id="bulb1" class="lightbulb">
<img src=".\images\bulb.png" class="none" />
</div>
<div id="bulb2" class="lightbulb">
<img src=".\images\bulb.png" class="none" />
</div>
<div id="bulb3" class="lightbulb">
<img src=".\images\bulb.png" class="none" />
</div>
<div id="bulb4" class="lightbulb">
<img src=".\images\bulb.png" class="none" />
</div>
Here is the fiddle.
With the help of Hiral and some more googling I implemented my functionality. Below is my final showBulbImage function
function showBulbImages()
{
var blink_count = 0;
var myArray = ['1', '2', '3', '4'];
var randomArray = shuffleArray(myArray)
var blink_the_bulbs = setInterval(function() {
var blinking_bulb = "bulb" + randomArray[blink_count];
document.getElementById(blinking_bulb).style.visibility = "visible";
blink_count+=1;
if (blink_count > 3)
{
clearInterval(blink_the_bulbs);
}
}, 1000);
}
function shuffleArray(array)
{
for (var i = array.length - 1; i > 0; i--)
{
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}