What is wrong with my image slide show code? - javascript

I'm trying to make an image cycle through a set of images, when you click a button. Why won't it work? I want to make sure the images are preloaded, so that it will not make the website slower.
var ImageSet = new Array();
ImageSet[0] = ImageOne;
ImageOne = newImage();
ImageSet[0].src = 'Website/Images/CoverPhotos/LogoCover.jpg';
ImageSet[1] = ImageTwo;
ImageTwo = newImage();
ImageSet[1].src = 'http://p1.pichost.me/i/64/1886374.jpg';
ImageSet[2] = ImageThree;
ImageThree = newImage();
ImageSet[2].src = 'http://abduzeedo.com/files/originals/5/50cuteanimpic6.jpg';
ImageSet[3] = ImageFour;
ImageFour = newImage();
ImageSet[3].src = 'http://www.onsecrethunt.com/wallpaper/wp-content/uploads/2015/01/Cool-Wallpapers-Card-Pictures-1200x675.jpg';
var ImageSwitchNo = 0;
function Change() {
if (ImageSwitchNo < 3) {
ImageSwitchNo++;
}else {
ImageSwitchNo = 0;
}
var ImageSrc = document.getElementById('HeaderPhotoImage').innerHTML;
ImageSrc.src = ImageSet[3];
}

You are giving ImageOne a value on line three after trying to store it in the array on the line before it.
Instead of this:
var ImageSet = new Array();
ImageSet[0] = ImageOne;
ImageOne = newImage();
ImageSet[0].src = 'Website/Images/CoverPhotos/LogoCover.jpg';
try doing it like this for all of them:
var ImageSet = [];
ImageOne = newImage(); //gives ImageOne a value.
ImageSet[0] = ImageOne; //THEN sets the index of ImageSet to that value.
ImageSet[0].src = 'Website/Images/CoverPhotos/LogoCover.jpg';

Your code may work if you change the second line from bottom,
ImageSrc.src = ImageSet[3];
to
ImageSrc.src = ImageSet[ImageSwitchNo];

Related

Loading images with javascript

By clicking on the button , the random two pictures should appear of 12 included in two boxes.But something goes wrong.Need advice to solve this this problem.
var startBtn = document.getElementById("start-button");
var imgBox1 = document.getElementById("firstBox");
var imgBox2 = document.getElementById("secondBox");
var images = [
'/assets/img/pic1.png',
'/assets/img/pic2.png',
'/assets/img/pic3.png',
'/assets/img/pic4.png',
'/assets/img/pic5.png',
'/assets/img/pic6.png',
'/assets/img/pic7.png',
'/assets/img/pic8.png',
'/assets/img/pic9.png',
'/assets/img/pic10.png',
'/assets/img/pic11.png',
'/assets/img/pic12.png',
];
function loadImages(imgArr){
for(var i=0; i< imgArr.length; i++) {
console.log(imgArr[i]);
var img = new Image();
img.src = imgArr[i];
document.getElementById('output').appendChild(img);
}
}
startBtn.onclick = function(){
imgBox1.style.backgroundImage = images[Math.floor(Math.random()*images.length)];
imgBox2.style.backgroundImage = images[Math.floor(Math.random()*images.length)];
}
You need to use CSS's url function when setting the background image:
startBtn.addEventListener("click", function() {
imgBox1.style.backgroundImage = `url('${images[Math.floor(Math.random() * images.length)]}')`
imgBox2.style.backgroundImage = `url('${images[Math.floor(Math.random() * images.length)]}')`
});
You didn't add a button with id start-button by which you want to click. Essentially you are clicking on nothing.
<button type="button" id="start-button" style="">Start</button>

How do I determine which value has been called from an array, to use in another function?

I have the below code which is called onclick, and want to be able to show a second image after a few seconds, depending on which one is chosen from the array - so for example if 1.png is shown, then I want to show 1s.png, 2.png then show 2s.png etc
function displayImage () {
var img_name = new Array("images/1.png", "images/2.png", "images/3.png");
var l = img_name.length;
var rnd_no = Math.floor(l*Math.random());
document.getElementById("imgHolder").src = img_name[rnd_no];
}
How do I determine which image has been chosen from the array to then use in another function please ?
You're gonna need a global var for knowing that function is running for the first time or not.
var alreadyRandom = false;
function displayImage()
{
var img_name = new Array("images/1.png", "images/2.png", "images/3.png");
if(alreadyRandom)
{
// If the random for first time is done
var rnd_no = img_name.indexOf(document.getElementById("imgHolder").getAttribute('src'));
if(rnd_no === img_name.length-1)
{
// If the current image is the last one in array,
// go back to the first one
rnd_no = 0;
}
else
{
// Choose the next image in array
rnd_no++;
}
document.getElementById("imgHolder").src = img_name[rnd_no];
}
else
{
var l = img_name.length;
var rnd_no = Math.floor(l*Math.random());
document.getElementById("imgHolder").src = img_name[rnd_no];
alreadyRandom = true; // Tell the function not to random again
}
return img_name[rnd_no];
}
Demo: http://jsbin.com/kanejugahi/edit?html,js,console,output
Moreover, making the array global would make your function more efficient.
Hope this helps,
I think it's important you understand how Functions work in JavaScript and how scope works.
What you need to do is you need to expose that information so that both functions have access. You have the array of images defined and you have already determined the random number so just make them available by declaring them outside of the function so now these variables are available. Defining variables in the global scope is generally bad practice but this is simply for teaching.
var selectedImage; // defined outside so it is available for other functions
function displayImage() {
var img_name = new Array("images/1.png", "images/2.png", "images/3.png");
var rnd_no = Math.floor(img_name.length * Math.random());
selectedImage = img_name[rnd_no];
document.getElementById("imgHolder").src = selectedImage;
}
function anotherFunction() {
console.log(selectedImage);
}
As far as I understand the question, you can use a return and make the image array global.
var img_name = new Array("images/1.png", "images/2.png", "images/3.png");
var img_class = '';
//this function will return the index of the image in array
function displayImage () {
var l = img_name.length;
var rnd_no = Math.floor(l*Math.random());
document.getElementById("imgHolder").src = img_name[rnd_no];
return rnd_no;
}
var nextimage;
function showImages(){
//your logic to show the next image here
nextimage = (displayImage ()+1)%img_name.length;
var myVar = setInterval(function(){
if(img_class==''){
document.getElementById("imgHolder").src = img_name[nextimage];
img_class = 's';
}else{
var img_arr = img_name[nextimage].split(".");
if(img_arr.length===2){
document.getElementById("imgHolder").src = img_arr[0]+"s."+img_arr[1];
}
img_class = '';
nextimage = (nextimage+1)%img_name.length;
}
}, 1000);
}
var img_name = new Array("images/1.png", "images/2.png", "images/3.png");
var img_class = '';
//this function will return the index of the image in array
function displayImage () {
var l = img_name.length;
var rnd_no = Math.floor(l*Math.random());
document.getElementById("imgHolder").src = img_name[rnd_no];
return rnd_no;
}
var nextimage;
function showImages(){
//your logic to show the next image here
nextimage = (displayImage ()+1)%img_name.length;
var myVar = setInterval(function(){
if(img_class==''){
document.getElementById("imgHolder").innerHTML = img_name[nextimage];
img_class = 's';
}else{
var img_arr = img_name[nextimage].split(".");
if(img_arr.length===2){
document.getElementById("imgHolder").innerHTML = img_arr[0]+"s."+img_arr[1];
}
img_class = '';
nextimage = (nextimage+1)%img_name.length;
}
}, 1000);
}
showImages();
<div id="imgHolder"></div>
Mayve something like this?
var images = ["images/1.png", "images/2.png", "images/3.png"];
function displayImage () {
var dom = document.getElementById("imgHolder");
if ( images.indexOf(dom.src) >=0 ) {
dom.src = dom.src.replace(".png", "s.png"); // Seems like a stupid way to do this
return;
}
var l = images.length;
dom.src = images[Math.floor(l*Math.random())];
}

Js function always return the same values

Js beginner here.
I have a function like this:
generateSteps: function() {
var stepsLength = this.data.steps.length;
var dataStepsInit = this.data.steps;
for (var i = 0; i < stepsLength; i++) {
var stepsItem = dataStepsInit[i].ITEM;
var arrayItem = this.animationNodes[stepsItem - 1];
var transition = this.animationParameters[i].transition;
var options = this.animationParameters[i].options;
var speed = this.animationParameters[i].speed;
var delay = this.animationParameters[i].delay;
arrayItem.delay(delay).show(transition, options, speed);
if (dataStepsInit[i].AUDIOID) {
var audioClass = dataStepsInit[i].AUDIOID;
var audioPlayer = this.template.find("audio." + audioClass);
setTimeout(playAudioOnDelay,delay);
};
var playAudioOnDelay = function() {
audioPlayer[0].pause();
audioPlayer[0].currentTime = 0;
audioPlayer[0].play();
};
}
}
What it does is generate data from JSON and display animated elements one by one on delay. Animation part work fine. I can assign required animations and delay to DOM elements and show them in right order.
But what I want to do in the same time is also to play an audio on delay (so I use setTimeout). Everything is almost fine, I play audio in right time (correct delay value) but I always play the same audio (which is last element) because audioPlayer always is the same DOM node.
I think this have something to do with this or I mixed a scope?
Try this:
generateSteps: function() {
var stepsLength = this.data.steps.length;
var dataStepsInit = this.data.steps;
for (var i = 0; i < stepsLength; i++) {
var stepsItem = dataStepsInit[i].ITEM;
var arrayItem = this.animationNodes[stepsItem - 1];
var transition = this.animationParameters[i].transition;
var options = this.animationParameters[i].options;
var speed = this.animationParameters[i].speed;
var delay = this.animationParameters[i].delay;
arrayItem.delay(delay).show(transition, options, speed);
if (dataStepsInit[i].AUDIOID) {
var audioClass = dataStepsInit[i].AUDIOID;
var audioPlayer = this.template.find("audio." + audioClass);
setTimeout(playAudioOnDelay(audioPlayer),delay);
};
}
function playAudioOnDelay(audioPlayer){
return function(){
audioPlayer[0].pause();
audioPlayer[0].currentTime = 0;
audioPlayer[0].play();
}
}
}
Essentially, your problem looks like this: http://jsfiddle.net/po0rLnwo/
The solution is : http://jsfiddle.net/gpfuo1s8/
Check the console in your browser.

Can't get form total cost

So I have a form with two dropdowns. The first dropdown is the options, and the other is more options. So it's like a mix and match, now I want to calculate the total from the two selected dropdowns. Here's what I got going
var repairCost = new Array();
repairCost["none_repair"] = 0;
repairCost["minor"] = 10;
repairCost["major"] = 20;
repairCost["extreme"] = 30;
var colorCost = new Array();
colorCost["none_color"] = 0;
colorCost["single_portrait"] = 10;
colorCost["group_scene"] = 20;
$("#repair_drop").change(function (event) {
getRepair();
function getRepair(){
var repair = 0;
var form = document.forms["myform"];
var selectedRepair = form.elements["repair_drop"];
repair = repairCost[selectedRepair.value];
return repair
}
});
$("#colorize_drop").change(function (event) {
getColor();
function getColor(){
var color = 0;
var form = document.forms["myform"];
var selectedColor = form.elements["colorize_drop"];
color = colorCost[selectedColor.value];
return color
}
});
var timer1 = null;
clearTimeout(timer1);
timer1 = setTimeout(total, 500)
function total(){
var cost = getRepair() + getColor();
console.log(cost);
}
total();
I end up getting
Uncaught ReferenceError: getRepair is not defined
So for example I'd choose repairCost["minor"] and colorCost["group_scene"], then my result would be $30. I have a timer in there so it automatically calculates the total. Any ideas?
You defined the getRepair function inside another function. Therefore you cannot access it from outside. You have to define it outside the function to be able to access it, like so :
var repairCost = new Array();
repairCost["none_repair"] = 0;
repairCost["minor"] = 10;
repairCost["major"] = 20;
repairCost["extreme"] = 30;
var colorCost = new Array();
colorCost["none_color"] = 0;
colorCost["single_portrait"] = 10;
colorCost["group_scene"] = 20;
function getRepair(){
var repair = 0;
var form = document.forms["myform"];
var selectedRepair = form.elements["repair_drop"];
repair = repairCost[selectedRepair.value];
return repair;
}
function getColor(){
var color = 0;
var form = document.forms["myform"];
var selectedColor = form.elements["colorize_drop"];
color = colorCost[selectedColor.value];
return color;
}
$("#repair_drop").change(function (event) {
getRepair();
});
$("#colorize_drop").change(function (event) {
getColor();
});
var timer1 = null;
clearTimeout(timer1);
timer1 = setTimeout(total, 500)
function total(){
var cost = getRepair() + getColor();
console.log(cost);
}
Why are you declaring functions within your events, and then calling them from there? Either declare them outside the events, or just inline the code - don't do both.

How to change the position randomly?

var imgOut = function(){
var outImg = Math.floor(Math.random()*slideRandom.length);
document.getElementById("random").src = imgRandom[outImg];
var outSlide = slideRandom[outImg];
outSlide();
var wr = Math.floor(Math.random()*imgRandom.length);
var btl = Math.floor(Math.random()*bottle.length);
document.getElementById("bottle2").src = bottle[outImg];
document.getElementById("bottle1").src = bottle[btl];
document.getElementById("bottle3").src = bottle[wr];
/* try below but doesn't work or syntax error occured*/
var position= ['bottle[outImg]','bottle[btl]','bottle[wr]'];
var pos = Math.floor(Math.random()*position.length);
var pos1 = position[pos];
pos1();
}
what I'm try to do is
with different arrays to get different each images in different random position.
I've done different images to get but with three different arrays to put in random position doesn't work. what have I done wrong? or how to change above code?
I don't understand your requirements exactly, but consider this code:
var setImage = function(id, src) {
document.getElementById(id).src = src;
};
var chooseOne = function(array) {
return array[Math.floor(Math.random()*array.length)];
};
var setRandomImages = function() {
setImage("bottle1", chooseOne(bottle));
setImage("bottle2", chooseOne(bottle));
setImage("bottle3", chooseOne(bottle));
};
If the array bottle is a list of URLs, this will do something, though I cannot guarantee it will do what you want.
var position= ['bottle[outImg]()','bottle[btl]()','bottle[wr]()'];
var pos = Math.floor(Math.random()*position.length);
var pos1 = position[pos];
//pos1();
eval( pos1 );
// or
(new Function("return pos1"))();

Categories