<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="Red.jpg" width="209" height="241">
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
<script>
index=(0)
var traffic = ["Red","Rambo","Green","Yellow"]
function changeImage() {
var image = document.getElementById('Light');
if traffic[index] === "Red" {
image.src = "Rambo.jpg";
index= (index+1)
} else if traffic[index] === "Rambo" {
image.src = "Green.jpg";
index= (index+1)
} else if traffic[index] === "Green" {
image.src = "Yellow.jpg";
index= (index+1)
} else {
image.src = "Red.jpg";
index=0
}
}
</script>
</html>
</body>
this is my code I don't understand why when i click the button the image doesn't change the images are all .jpg files are all contained inside the same folders and all are the same size any ideas why is will not change the image i'm currently guessing it's something to do with the === or the fact i'm using words instead of numbers for them
Lots of things going wrong here:
Parenthese around the if statements
Closing body tag after closing html tag
document.getElementById does not get the same id as the img id
So, this will work, but perhaps checking the javascript and HTML syntax first might be a good start:
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="Red.jpg" width="209" height="241">
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
<script>
var index = 0;
var traffic = ["Red","Rambo","Green","Yellow"];
var image = document.getElementById('myImage');
function changeImage() {
if (traffic[index] === "Red") {
image.src = "Rambo.jpg";
index++;
} else if (traffic[index] === "Rambo") {
image.src = "Green.jpg";
index++;
} else if (traffic[index] === "Green") {
image.src = "Yellow.jpg";
index++;
} else {
image.src = "Red.jpg";
index = 0;
}
}
</script>
</body>
</html>
There are few little mistakes in your code.
The id of your image is myImage, but you wrote var image = document.getElementById('Light'); which result on undefined.
As mentioned by PierreDuc, you missed parenthesis around if conditions.
Take a look at this example : https://jsfiddle.net/1wjn943x/
var images = [
"http://openphoto.net/thumbs2/volumes/mylenebressan/20120720/openphotonet_11.jpg",
"http://openphoto.net/thumbs2/volumes/sarabbit/20120322/openphotonet_DSCF5890.JPG",
"http://openphoto.net/thumbs2/volumes/Sarabbit/20120117/openphotonet_gerberadaisy3.jpg"
];
var index = 0;
var img = document.getElementById("myImage");
document.getElementById("button").addEventListener('click', function() {
// Next image.
index = (index + 1) % images.length;
// Setting `src`attribute of <img>.
img.src = images[index];
});
This is the easiest way to change the image.
Simply set the image source to be the next image in the array. You need to use the mod operator to loop from the end; back to the beginning.
Array - Index Pointer
var imageEl = document.getElementById('Light');
var index = 0;
var images = [
"http://placehold.it/150x150/FF0000/FFFFFF.jpg?text=Red",
"http://placehold.it/150x150/0000FF/FFFFFF.jpg?text=Rambo",
"http://placehold.it/150x150/00FF00/FFFFFF.jpg?text=Green",
"http://placehold.it/150x150/FFFF00/FFFFFF.jpg?text=Yellow"
];
function changeImage() {
imageEl.src = images[index++ % images.length]; // Set and increment the image index.
}
changeImage();
<img id="Light" width="150" height="150">
<br />
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
Map - Linked Pointer
var imageEl = document.getElementById('Light');
var currImage = '';
var images = {
red : {
src : "http://placehold.it/150x150/FF0000/FFFFFF.jpg?text=Red",
next : 'rambo'
},
rambo : {
src : "http://placehold.it/150x150/0000FF/FFFFFF.jpg?text=Rambo",
next : 'green'
},
green : {
src : "http://placehold.it/150x150/00FF00/FFFFFF.jpg?text=Green",
next : 'yellow'
},
yellow : {
src : "http://placehold.it/150x150/FFFF00/FFFFFF.jpg?text=Yellow",
next : 'red'
}
};
function changeImage() {
(function(img) {
imageEl.src = img.src; // Set the image source to the current image.
currImage = img.next; // Set current image as the next image.
}(images[currImage || 'red']));
}
changeImage();
<img id="Light" width="150" height="150">
<br />
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
Class - Circular Iterator
var CircularIterator = function(iterable) {
this.iterable = iterable || [];
this.index = 0;
this.get = function(index) {
return this.iterable[index] || this.next();
};
this.size = function() {
return this.iterable.length;
};
this.incr = function() {
return this.index = ((this.index + 1) % this.size());
};
this.next = function() {
return this.get(this.incr());
};
this.first = function() {
return this.get(0);
};
this.last = function() {
return this.get(this.size() - 1);
};
};
var imageEl = document.getElementById('Light');
var iterable = new CircularIterator([
"http://placehold.it/150x150/FF0000/FFFFFF.jpg?text=Red",
"http://placehold.it/150x150/0000FF/FFFFFF.jpg?text=Rambo",
"http://placehold.it/150x150/00FF00/FFFFFF.jpg?text=Green",
"http://placehold.it/150x150/FFFF00/FFFFFF.jpg?text=Yellow"
]);
function changeImage() {
imageEl.src = iterable.next(); // Set and increment the image index.
}
imageEl.src = iterable.first(); // Set the current image to the first.
<img id="Light" width="150" height="150">
<br />
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
Related
I'm trying to make an image that switches between two sources every two seconds but the image isn't changing
<img id="bannerPic" src="banner1.jpg">
<script>
var pic = document.getElementById('bannerPic').src;
setInterval(function(){
if(pic == 'banner1.jpg'){
pic = 'banner2.jpg';
console.log('change1');
}
else{
pic = 'banner1.jpg';
console.log('change2');
}
}, 2000);
</script>
You're assigning a value to a variable rather than the attribute src.
You need to set the new value to the attribute src
To check for the current url, using this: img.src.indexOf('banner1.jpg')
var img = document.getElementById('bannerPic');
setInterval(function() {
if (img.src.indexOf('banner1.jpg') !== -1) {
img.src = 'banner2.jpg';
console.log('change1');
} else {
img.src = 'banner1.jpg';
console.log('change2');
}
}, 2000);
<img id="bannerPic" src="banner1.jpg">
<img id="bannerPic" src="banner1.jpg">
<script>
var pic = document.getElementById('bannerPic')
console.log(pic.src)
setInterval(function(){
if(pic.src == 'https://stacksnippets.net/banner1.jpg'){
pic.src = 'https://stacksnippets.net/banner2.jpg';
console.log('change1');
}
else{
pic.src = 'https://stacksnippets.net/banner1.jpg';
console.log('change2');
}
}, 2000);
</script>
What I'm trying to achieve: clicking on any image should either reveal a clear image if image is blurred or blur the image if image is clear
What's happening: clicking on blurred image clears the image, but clicking on it again does nothing. so, clicking on a clear image does not blur it (as it should).
Here's my code:
<script>
window.onload = init;
function init(e) {
var img = document.getElementsByTagName("img");
//var img = document.getElementById('pics');
img[0].onclick = unblur; // <- why not just img.onclick = unblur ??
img[1].onclick = unblur;
img[2].onclick = unblur;
console.log(img);
/*
var imageId = e.target.id; //zero
var img = document.getElementById(imageId);
*/
//img.onclick = unblur;
}
function unblur(e) {
var imageId = e.target.id; //zero
var img = document.getElementById(imageId);
var imageSource = img.src; //zeroblur.jpg
var clearImg = imageSource.substring(0, imageSource.length - 8);
var unblurredImg = imageId.concat('.jpg'); // zero.jpg
var blurredImg = imageId.concat('blur.jpg'); // zeroblur.jpg
console.log(imageSource);
console.log(img.src);
//console.log(imageSource);
if (img.src == unblurredImg) {
img.src = blurredImg;
} else {
img.src = unblurredImg; // image is clear, so hide the pic
}
/*
if (img.src == blurredImg) {
img.src = unblurredImg;
}
} */
//}
}
/*
//if (!(imageId instanceof img)) {
if (imageId !== "pics") {
if (img.src == blurredImg) {
img.src = unblurredImg;
} else if (img.src == unblurredImg) {
img.src = blurredImg;
} // image is blurred, so reveal the pic
else {
console.log("hi");
}
//debugger;
}
}
*/
/*
var img = document.getElementById('zero');
img.src = "zero.jpg";
*/
</script>
</head>
<body>
<div id="pics">
<img id="zero" src="zeroblur.jpg">
<img id="one" src="oneblur.jpg">
<img id="two" src="two.jpg">
</div>
</body>
</html>
I also noticed that if I switch the conditions in the function, unblur(e), to the following...
if (img.src == unblurredImg) {
img.src = blurredImg;
} else {
img.src = unblurredImg;
}
there's no response at all if a user clicks on a blurred image, whereas before (code above) the blurred image will at least reveal the cleared image.
Why is this happening? I see no difference between the two, besides just switching the order of the conditions.
There are various mistakes in your example. Take a look at the Code Snippet for a working example of what you are trying to achieve.
As for your comment:
// <- why not just img.onclick = unblur ??
Because document.getElementsByTagName returns an array of elements. Therefore, you must iterate through the elements to apply the onclick handlers to each one.
(function(document) {
var array = document.getElementsByTagName("img");
for (var i = 0; i < array.length; i++) {
array[i].onclick = toggleBlur;
}
function toggleBlur(event) {
var img = event.target;
var oldSrc = img.src; // Save to display in the console
if (img.src.endsWith("blur.jpg")) {
img.src = img.id + ".jpg";
} else {
img.src = img.id + "blur.jpg"
}
console.log(oldSrc + " -> " + img.src + " on element.id=" + img.id);
}
})(document);
<body>
<div id="pics">
<img id="zero" src="zero.jpg">
<img id="one" src="one.jpg">
<img id="two" src="twoblur.jpg">
</div>
</body>
I want to swap images using JavaScript. When only section1 is used the swapping of image works but when section2 is added then the swapping of image works only on section2(stops swapping in section1).
Codes are:
JavaScript
--section1--
var imagetracker="m";
function change(){
var image=document.getElementById('image1');
if(imagetracker=="m"){
image.src="images/momo 2.jpg";
imagetracker="t";
}else if(imagetracker=='t'){
image.src="images/taco.jpg";
imagetracker="m";
}
}
var timer = setInterval('change()',2000);
--section2--
var imagetracker="p2";
function change2(){
var image=document.getElementById('image2');
if(imagetracker=="p2"){
image.src="images/pizza 2.jpg";
imagetracker="b";
}else if(imagetracker=='b'){
image.src="images/burrito 2.jpg";
imagetracker="p2";
}
}
var timer2 = setInterval('change2()',2000);
HTML
<img src="images/momo 2.jpg" height="150" width="220" id="image1">
<img src="images/pizza 2.jpg" height="150" width="220" id="image2"><p>
How should be done to make section1 work?
You have two imagetracker variables. Rename either one so that there is one of each.
You assign imagetracker to "m" and "p2" which will cause an error because there are two defined variables of the same name.
You can change the setInterval lines to:
var timer = setInterval(change, 2000);
This gives the function as a parameter and sets the interval to run change() every 2 seconds. This also applies to the second timer.
Your version is fine and strings are fine to be passed as functions.
Here is a reference on the setInterval function from W3Schools
Since you are using same imagetracker variable for both, it may cause problem since values are different. So use different variables for both, that may fix your problem.
var imagetracker = "m";
function change() {
var image = document.getElementById('image1');
if (imagetracker == "m") {
image.src = "images/momo 2.jpg";
imagetracker = "t";
} else if (imagetracker == 't') {
image.src = "images/taco.jpg";
imagetracker = "m";
}
}
var timer = setInterval('change()', 2000);
var imagetracker1 = "p2";
function change2() {
var image = document.getElementById('image2');
if (imagetracker1 == "p2") {
image.src = "images/pizza 2.jpg";
imagetracker1 = "b";
} else if (imagetracker1 == 'b') {
image.src = "images/burrito 2.jpg";
imagetracke1r = "p2";
}
}
var timer2 = setInterval('change2()', 2000);
<img src="images/momo 2.jpg" height="150" width="220" id="image1">
<img src="images/pizza 2.jpg" height="150" width="220" id="image2">
<p>
Also instead of the string param you can use function reference as argument, that may be much better way to do it.
var timer2 = setInterval(change, 2000);
FYI : String of code is not recommenced because that have lot of security problems, since it's working using eval().
Refer : Why is using the JavaScript eval function a bad idea?
Too unscalable code.
Let's try fix it :)
function rotImg(id, urls) {
var img = document.getElementById(id);
var index = -1;
return function() {
if (++index >= urls.length) index = 0;
img.src = urls[index];
};
}
setInterval(rotImg('image1', [
'images/momo 2.jpg',
'images/taco.jpg'
]), 2000);
setInterval(rotImg('image2', [
'images/pizza 2.jpg',
'images/burrito 2.jpg'
]), 2000);
function rotImg(id, urls) {
var img = document.getElementById(id);
var index = -1;
return function() {
if (++index >= urls.length) index = 0;
img.src = urls[index];
};
}
setInterval(rotImg('image1', [
'https://placekitten.com/200/300',
'https://placekitten.com/200/301',
'https://placekitten.com/201/300'
]), 2000);
setInterval(rotImg('image2', [
'https://placekitten.com/300/200',
'https://placekitten.com/300/201',
'https://placekitten.com/301/200'
]), 2000);
<img src="https://placekitten.com/201/300" height="220" id="image1">
<img src="https://placekitten.com/301/200" height="220" id="image2">
I'm doing some code with changing images in an array, I've got to the point where the images change automatically but I want to get different times between the images as they change. I am writing the code in Dreamweaver.
Here is the code as it is now:
<!DOCTYPE html>
<html>
<body>
<img src="image1.png" width="74" height="208" id="image1">
<br>
<button onclick="clearInterval(MyVar)">Stop Sequence</button>
<script>
MyVar = setInterval(ChangeImages, 1000)
function Start() {
myVar = setInterval(ChangeImages, 1000)
}
var Images = ["image1.png", "image2.png","image3.png","image4.png"];
var image = document.getElementById("image1");
function ChangeImages()
{
if (image1.src.match(Images[0]))
{
image.src = Images[1];
} else if (image1.src.match(Images[1]))
{
image.src = Images[2];
} else if (image1.src.match(Images[2]))
{
image.src = Images[3];
} else if (image1.src.match(Images[3]))
{
image.src = Images[0];
}
}
</script>
<br>
<Button onclick="Start() ">Resume</button>
</body>
</html>
Any help will be greatly appreciated.
Thanks
If you want to change the number of seconds every time you could use setTimeout instead of setInterval and then do a callback at the end of ChangeImages. And use a random number generator to get the amount of milliseconds. In the example below I set it to 1000, 2000 or 3000 milliseconds.
<img src="image1.png" width="74" height="208" id="image1">
<br>
<button onclick="clearInterval(myVar)">Stop Sequence</button>
<script>
function Start() {
myVar = setTimeout(ChangeImages, randomInterval(1,3));
}
var Images = ["image1.png", "image2.png","image3.png","image4.png"];
var image = document.getElementById("image1");
function randomInterval(min,max)
{ var number = (Math.floor(Math.random()*(max-min+1)+min))*1000;
console.log(number);
return number;
}
function ChangeImages(){
if (image1.src.match(Images[0])){
image.src = Images[1];
}
else if (image1.src.match(Images[1])){
image.src = Images[2];
}
else if (image1.src.match(Images[2])){
image.src = Images[3];
}
else if (image1.src.match(Images[3])){
image.src = Images[0];
}
Start();
}
</script>
<br>
<Button onclick="Start() ">Resume</button>
EDIT
function Start(timeout) {
myVar = setTimeout(ChangeImages, timeout);
}
var Images = ["image1.png", "image2.png","image3.png","image4.png"];
var image = document.getElementById("image1");
function ChangeImages(){
if (image.src.match(Images[0])){
image.src = Images[1];
Start(1000);
}
else if (image.src.match(Images[1])){
image.src = Images[2];
Start(2000);
}
else if (image.src.match(Images[2])){
image.src = Images[3];
Start(3000);
}
else if (image.src.match(Images[3])){
image.src = Images[0];
Start(4000);
}
}
I am not into javascript, but I really want randomized pictures on my index page so was wondering if there is anything I could do with my current javascript to add image link to each picture?
< img id = "reklame" / >
< script >
function getRandomImage() {
var images = ['bilder/reklame.jpg', 'bilder/reklame1.jpg', 'bilder/reklame2.jpg', 'bilder/reklame3.jpg'];
var image = images[Math.floor(Math.random() * images.length)];
return image;
}
function displayRandomImage() {
var htmlImage = document.getElementById("reklame");
htmlImage.src = getRandomImage();
}
displayRandomImage(); < /script>
You can do that with the setInterval function
//First call
displayRandomImage();
var loop = setInterval(function() {
//Call each 5 seconds
displayRandomImage()
}, 5000);
jsFiddle
hope this will work:
<html>
<head></head>
<body>
<div id = "reklame">
<img / >
</div>
<script type="text/javascript">
function getRandomImage() {
var images = ['bilder/reklame.jpg', 'bilder/reklame1.jpg', 'bilder/reklame2.jpg', 'bilder/reklame3.jpg'];
var image = images[Math.floor(Math.random() * images.length)];
return image;
}
function displayRandomImage() {
var imgDiv = document.getElementById("reklame");
var image = imgDiv.getElementsByTagName('img')[0];
image.src = getRandomImage();
var a=document.createElement('a');
a.href=getRandomImage();
a.appendChild(image);
imgDiv.appendChild(a);
}
window.setInterval(function(){
displayRandomImage();
}, 5000);
</script>
</body>
</html>
Call your displayRandomImage() inside setInterval()
window.setInterval(function(){
displayRandomImage();
}, 5000);
try this fiddle - http://jsfiddle.net/yellen/twf16y5a/4/
Fiddle updated to link a url with each image
function getRandomImage() {
var images = [{
"image": "http://freethumbs.dreamstime.com/8/big/free_89634.jpg",
"url": "http://www.google.com"
}, {
"image": "http://freethumbs.dreamstime.com/14/big/free_144227.jpg",
"url": "http://www.facebook.com"
}, {
"image": "http://freethumbs.dreamstime.com/22/big/free_229201.jpg",
"url": "http://www.stackoverflow.com"
}]
// You'd like store the image path and the url as a single object and have an array of that
//images = [{img, url},{img, url}]
var image = images[Math.floor(Math.random() * images.length)];
return image;
}
function displayRandomImage() {
var htmlImage = document.getElementById("reklame");
var link = document.getElementById("myuA");
var imageObj = getRandomImage();
htmlImage.src = imageObj.image;
link.href = imageObj.url;
}
displayRandomImage();
window.setInterval(function() {
displayRandomImage();
}, 5000);
<a id="myuA" href="" target="_blank">
<img id="reklame" />
</a>
Maybe something like this?
<a id="reklame-link" href="#";>
<img id = "reklame" />
function displayRandomImage() {
var htmlImage = document.getElementById("reklame");
var htmlLink = document.getElementById("reklame-link");
var randomImage = getRandomImage();
htmlImage.src = randomImage;
htmlLink.href = randomImage;
console.log(getRandomImage());
}
http://jsfiddle.net/y7rwhmd7/