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/
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 have searched a few results regarding this issue but none of them works for me, so I am posting here to get some helps. Basically my issue is when I clicked on the generate button, I want the image from canvas to be displayed in a img element. However, the image will show up in chrome but not firefox! Below is my coding...
<body onload="onLoad();">
<canvas id="aimage">Your browser does not support the canvas tag.</canvas>
<input type="button" value="Generate" onclick="genImage();" />
<img id="cImg" name="cImg" src="${param.src}" />
...
</body>
And the javascript...
var tcanvas;
var scanvas;
var tcontext;
var imageURL;
function onLoad() {
tcanvas = document.getElementById("aimage");
tcontext = tcanvas.getContext("2d");
scanvas = document.getElementById("cImg");
imageURL = "${param.src}";
update();
}
function update() {
var image = new Image();
image.onload = function () {
if (image.width != tcanvas.width)
tcanvas.width = image.width;
if (image.height != tcanvas.height)
tcanvas.height = image.height;
tcontext.clearRect(0, 0, tcanvas.width, tcanvas.height);
tcontext.drawImage(image, 0, 0, tcanvas.width, tcanvas.height);
}
image.crossOrigin = 'anon';
image.src = imageURL;
}
function genImage() {
var url = tcanvas.toDataURL("image/jpeg");
scanvas.crossOrigin = 'anon';
scanvas.src = url;
if(scanvas.width > 1000){
scanvas.width = 1000;
}
if(scanvas.height > 1000){
scanvas.height = 1000;
}
}
try this:
var scanvas, tcontext, tcanvas;
function genImage() {
var url = tcanvas.toDataURL("image/jpeg");
scanvas.src = url;
if (scanvas.width > 1000) {
scanvas.width = 1000;
}
if (scanvas.height > 1000) {
scanvas.height = 1000;
}
}
window.onload = function () {
tcanvas = document.getElementById("aimage");
tcontext = tcanvas.getContext("2d");
scanvas = document.getElementById('cImg');
var img = new Image();
img.onload = function () {
tcontext.drawImage(img, 0, 0, img.width, img.height)
};
img.src = "yourImage.jpg";
}