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">
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>
<!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>
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 have 2 pictures for my website, and i want it to load one of them whem the website loads.
I have tried using some javascript. But i am quite new to all this.
This is how i am think i want to make it.
<div class="image">
Show one of 2 images here.
</div>
<script>
var r = Math.floor(Math.random() * 100) + 1;
if(r < 51) {
SHOW IMAGE 1
}
else {
SHOWIMAGE 2
}
</sccript>
So i was hoping someone could teach me how to actually turn this into functional code.
Thanks.
You can set the src attribute of an image directly using javascript, then use Math.random like you expected to pick between different image urls.
With an image tag with id 'random_image':
// images from wikipedia featured images/articles 2015-03-03
var img = document.getElementById('random_image');
if (Math.random() > .5) {
img.src = 'http://upload.wikimedia.org/wikipedia/en/thumb/4/45/Bradford1911.jpg/266px-Bradford1911.jpg';
} else {
img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/Pitta_sordida_-_Sri_Phang_Nga.jpg/720px-Pitta_sordida_-_Sri_Phang_Nga.jpg';
}
Here is a jsfiddle example: http://jsfiddle.net/8zd5509u/
1.way:
var _img = document.getElementById('id1');
var newImg = new Image;
newImg.onload = function() {
_img.src = this.src;
}
newImg.src = 'http://www.something.blabla.....';
another:
function preload(images) {
if (document.images) {
var i = 0;
var imageArray = new Array();
imageArray = images.split(',');
var imageObj = new Image();
for(i=0; i<=imageArray.length-1; i++) {
//document.write('<img src="' + imageArray[i] + '" />');// Write to page (uncomment to check images)
imageObj.src=imageArray[i];
}
}
}
Then in the of each web page, add the following code after you've called the main JavaScript file:
<script type="text/javascript">
preload('image1.jpg,image2.jpg,image3.jpg');
</script>
I'm building a navigation bar where the images should be swapped out on mouseover; normally I use CSS for this but this time I'm trying to figure out javascript. This is what I have right now:
HTML:
<li class="bio"><img src="images/nav/bio.jpg" name="bio" /></li>
Javascript:
if (document.images) {
var bio_up = new Image();
bio_up.src = "images/nav/bio.jpg";
var bio_over = new Image();
bio_over.src = "images/nav/bio-ov.jpg";
}
function over_bio() {
if (document.images) {
document["bio"].src = bio_over.src
}
}
function up_bio() {
if (document.images) {
document["bio"].src = bio_up.src
}
}
However, all of the images have names of the form "xyz.jpg" and "xyz-ov.jpg", so I would prefer to just have a generic function that works for every image in the navbar, rather than a separate function for each image.
A quick-fire solution which should be robust enough provided all your images are of the same type:
$("li.bio a").hover(function() {
var $img = $(this).find("img");
$img[0].src = $img[0].src.replace(".jpg", "") + "-ov.jpg";
}, function() {
var $img = $(this).find("img");
$img[0].src = $img[0].src.replace("-ov.jpg", "") + ".jpg";
});
This should work will all image formats as long as the extension is between 2 and 4 characters long IE. png, jpeg, jpg, gif etc.
var images = document.getElementById('navbar').getElementsByTagName('img'), i;
for(i = 0; i < images.length; i++){
images[i].onmouseover = function(){
this.src = this.src.replace(/^(.*)(\.\w{2,4})$/, '$1'+'-ov'+'$2');
}
images[i].onmouseout = function(){
this.src = this.src.replace(/^(.*)-ov(\.\w{2,4})$/, '$1'+'$2');
}
}
Here's an idea in plain javascript (no jQuery):
function onMouseOverSwap(e) {
e.src = e.src.replace(/\.jpg$/", "-ov.jpg"); // add -ov onto end
}
function onMouseOutSwap(e) {
e.src = e.src.replace(/(-ov)+\.jpg$/, ".jpg"); // remove -ov
}