Javascript Automatic Image Swap w/ Multiple Arrays - javascript

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>

Related

hyperlinking an image in an array from another array

I have 2 arrays,I with images and another with links.
Using set interval I am changing the image in 2000millisec.
How can I hyperlink the image with the links.
var img_array = <?php echo json_encode($images); ?>;
var link_array = <?php echo json_encode($links); ?>;
var image = document.getElementById("aaa");
var index=0;
function slide(){
document["aaa"].src = img_array[index];
index++;
if(index>=img_array.length)
{
index=0;
}
}
setInterval("slide()",2000);
</script>
Here's an example. It's not perfect, because if you see it in the first time, the image is not loaded. This is why most of the sites generates all the images with links, and then just hide and show them.
var img_array = ["https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg", "https://images.pexels.com/photos/46710/pexels-photo-46710.jpeg", "https://images.unsplash.com/photo-1529736576495-1ed4a29ca7e1"];
var link_array = ["index1.html","index2.html","index3.html"];
var image = document.getElementById("image");
var link = document.getElementById("link");
// The first (which is the 0) is already loaded, so we need to skip it from here.
var index = 1;
function slide(){
image.src = img_array[index];
link.href = link_array[index];
index++;
if(index >= img_array.length) {
index=0;
}
}
setInterval(slide, 2000);
<img src="https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg" id="image" width="200">
Or if you can't change the DOM or you want to hide somewhy the url you can do something like this:
var img_array = ["https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg", "https://images.pexels.com/photos/46710/pexels-photo-46710.jpeg", "https://images.unsplash.com/photo-1529736576495-1ed4a29ca7e1"];
var link_array = ["index1.html","index2.html","index3.html"];
var image = document.getElementById("image");
// The first (which is the 0) is already loaded, so we need to skip it from here.
var index = 1;
function slide(){
image.src = img_array[index];
index++;
if(index >= img_array.length) {
index=0;
}
}
image.addEventListener("click", function() {
// This is because of the sandbox environment.
console.log(link_array[index]);
// This is what you need.
window.open(link_array[index]);
});
setInterval(slide, 2000);
.pointer {
cursor: pointer;
}
<img src="https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg" id="image" class="pointer" width="200">
However in this case maybe you will get blocked by the browser or if the click was registered after the new image was loaded, it may create a missclick.

how to change the picture on a page without a button or without hovering over it

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">

Why doesn't this mouseover/rollover work?

I have 3 images (pic1, pic2, pic3) that on click of the div ID change to (pic4, pic5, pic6). All this works fine but I need to put in a mouseover command that when hovering over pic2, it changes to pic 7 and on mouseout it goes back to pic 2. I am unsure as to why this part of my code isn't working, is it a syntax error? The two functions I am trying to use to do this are "rolloverImage" and "init".
HTML
<div id="content1">
<img src="pic1.jpg" alt="pic1"/>
<img src="pic2.jpg" alt="pic2" id="pic2"/>
<img src="pic3.jpg" alt="pic3"/>
</div>
Javascript
var g = {};
//Change background colors every 20 seconds
function changebackground() {
var backColors = ["#6AAFF7", "#3AFC98", "#FC9B3A", "#FF3030", "#DEDEDE"];
var indexChange = 0;
setInterval(function() {
var selectedcolor = backColors[indexChange];
document.body.style.background = selectedcolor;
indexChange = (indexChange + 1) % backColors.length;
}, 20000);
}
function rolloverImage(){
if (g.imgCtr == 0){
g.pic2.src = g.img[++g.imgCtr];
}
else {
g.pic2.src = g.img[--g.imgCtr];
}
}
function init(){
g.img = ["pic2.jpg", "pic7.jpg"];
g.imgCtr = 0;
g.pic2 = document.getElementById('pic2');
g.pic2.onmouseover = rolloverImage;
g.pic2.onmouseout = rolloverImage;
}
window.onload = function() {
var picSets = [
["pic1.jpg", "pic2.jpg", "pic3.jpg"],
["pic4.jpg", "pic5.jpg", "pic6.jpg"],
];
var currentSetIdx = 0;
var contentDiv = document.getElementById("content1");
var images = contentDiv.querySelectorAll("img");
refreshPics();
contentDiv.addEventListener("click", function() {
currentSetIdx = (currentSetIdx + 1) % picSets.length;
refreshPics();
});
function refreshPics() {
var currentSet = picSets[currentSetIdx];
var i;
for(i = 0; i < currentSet.length; i++) {
images[i].src = currentSet[i];
}
}
changebackground();
init();
}

How to choose random image from image set in javascript

I have been using the following code to generate random images, but none of the pictures are showing up.
<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
var theImages = new Array()
theImages[0] = '<img class="atvi-image-image" alt=""src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png" title="" height="467" width="675">'
theImages[1] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-zombies.png" title="" height="732" width="1084">'
theImages[2] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-extra-slots.png" title="" height="480" width="752">'
theImages[3] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-2025.png" title="" height="412" width="683">'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
document.write(theImages[whichImage]);
}
</script>
</head>
<body>
<SCRIPT LANGUAGE="JavaScript">
showImage();
</script>
</body>
</html>
Thank you in advance for your help!
You already have the full <img> tag in the array. So just use:
document.write(theImages[whichImage]);
Although I would advise against using document.write. Of course, in your situation, where it's being executed in the middle of HTML, I don't see much of a problem. It would be bad if document.write were executed after the page was rendered. Normally, the preferred method is something like the appendChild method or even setting innerHTML, although it would take some refactoring to get your code to use them.
Here's an example of how I'd set it up:
(function () {
var theImages = [{
src: "http://www.techinasia.com/techinasia/wp-content/uploads/2009/12/smile.png",
width: "675",
height: "467"
}, {
src: "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQdcHlJqgIKNOS0DaEjO31xK1zYtmJlza8z70ljiKFbo2ZgLdh9eA",
width: "1084",
height: "732"
}, {
src: "http://cdn2-b.examiner.com/sites/default/files/styles/large_lightbox/hash/68/d1/68d11ab242d40c8d5abbe8edb58fd4ed_0.jpg?itok=M3qtK47_",
width: "200",
height: "200"
}];
var preBuffer = [];
for (var i = 0, j = theImages.length; i < j; i++) {
preBuffer[i] = new Image();
preBuffer[i].src = theImages[i].src;
preBuffer[i].width = theImages[i].width;
preBuffer[i].height = theImages[i].height;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
window.getRandomImage = function () {
var whichImage = getRandomInt(0, preBuffer.length - 1);
return preBuffer[whichImage];
}
})();
window.onload = function () {
var newImage = getRandomImage();
console.log(newImage);
document.body.appendChild(newImage);
};
DEMO: http://jsfiddle.net/wFjGv/
This code uses a new object to hold the details for each image. That way, you can easily set and get each image's properties that you need without hardcoding HTML.
It preloads the images in the preBuffer array, and when needed, an image is retrieved from the array, and put into the <body>. You can change its target in the onload event. The getRandomImage function returns a random image from that array. I updated the method of getting a random integer as well.
You are setting an <img src= something that is not what you want. Your array (theImages) is storing full <img> tags, not just the link to that image.
Either change you theImages array to store values like so:
theImages[0] = "/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png"
OR use the current setup as the image tag.
document.write(theImages[whichImage]);
Also:
With random numbers, you should probably stick to Math.floor() lest
you round over your max length.
var j = 0 is missing a ;
theImages img tags are not closed (<img ... />
Try this-
var srcs = [
"/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png",
"/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-zombies.png",
"foo/bar.jpg"
], imgs = [];
function init() {
"use strict";
var i, x, div;
div = document.createElement('div');
div.id = 'imageContainer';
document.querySelector('body').appendChild(div);
for (i = 0; i < srcs.length; i += 1) {
x = new Image();
x.src = srcs[i];
imgs.push(x);
}
}
function showRandom() {
"use strict";
document.querySelector('#imageContainer').innerHTML = imgs[Math.random * imgs.length];
}
init();
To add a random image-
showRandom();
PS - You shouldn't use document.write, but if you do, you should close the stream by document.close, to tell the browser to finish loading the page. Read more - MDN JS Docs

Cycling between 3 images (mobile Safari)

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>

Categories