Make JavaScript change background image every 5 seconds - javascript

I am trying to change my background image every 5 seconds. How should I go about this?
window.onload = function () {
function Timer() {
window.setInterval("changeImage()", 5000);
}
function changeImage() {
var BackgroundImg["./Img/Bg1.jpg",
"./Img/Bg2.jpg",
"./Img/Bg3.jpg",
"./Img/Bg4.jpg"];
var i = Math.floor((Math.random() * 3));
var bgImg = document.body.style.backgroundImage();
bgImg.url = BackgroundImg[i];
}
}

You can make few changes
1.Not sure from where you are calling Timer function (better if
have camelCase)
function Timer() {
window.setInterval("changeImage()", 5000);
}
Instead you can directly use
setInterval(changeImage, 5000);
changeImage is a callback
2.Could not make out what is this line mean
var bgImg = document.body.style.backgroundImage();
Unsure if can attach a function to style property.
Anyway this below snippet can be useful
window.onload = function () {
// Array of Images
var backgroundImg=["https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRyB57zuc4bms-hDtWMa-4BZvscIlJDm4r7a9WLaO4SAxUvKM-DDA",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQBinSpWOvAtkxjmkf709O3rjH2ObRbWAEn9s0JcWaeL6LMtCbOrQ",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRKY4J2qIFqkuDnABMzeypywbMSZL1cleS8vpySz0KD02wOYORU1g",
"https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRQkdQT0zN0xDVP-VuvwojSbS5dOstX14eZvJCOWNPxKJ5dWTIc"
]
setInterval(changeImage, 5000);
function changeImage() {
var i = Math.floor((Math.random() * 3));
document.body.style.backgroundImage = "url('"+backgroundImg[i]+"')";
}
}
DEMO

you are accessing style incorrectly
window.onload = function () {
function changeImage() {
var BackgroundImg=["./Img/Bg1.jpg",
"./Img/Bg2.jpg",
"./Img/Bg3.jpg",
"./Img/Bg4.jpg"
];
var i = Math.floor((Math.random() * 4));
document.body.style.backgroundImage = 'url("' + BackgroundImg[i] + '")';
}
window.setInterval(changeImage, 5000);
}
Also, if possible (usually is) don't pass a string to window.setInterval - use as above

Here's a solution to your question. Hope it helps!
<!DOCTYPE html>
<html>
<head>
<title>change picture</title>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function changeImage() {
setInterval(displayNextImage, 5000);
}
var images = [], x = -1;
images[0] = "http://www.planwallpaper.com/static/images/desktop-year-of-the-tiger-images-wallpaper.jpg";
images[1] = "http://www.planwallpaper.com/static/images/background-gmail-google-images_FG2XwaO.jpg";
images[2] = "http://www.planwallpaper.com/static/images/beautiful-sunset-images-196063.jpg";
</script>
</head>
<body onload = "changeImage()">
<img id="img" src="http://www.planwallpaper.com/static/images/beautiful-sunset-images-196063.jpg"/>
</body>
</html>

Related

displaying one image, then another using HTML

I asked a similar question elsewhere, but I am trying to switch from one image to the next after 500 ms. Somebody provided this answer, but the code only works when I preview it in the HTML and Javascript boxes of the site i'm using (then displays nothing when I launch it):
<html>
<head>
<title>switch</title>
<script type = "text/javascript">
var images = [];
var x = 0;
var $img = document.getElementById("img");
images[0] = "image1.jpg";
images[1] = "image2.jpg";
function displayNextImage() {
if (++x < images.length) {
$img.src = images[x];
setInterval(displayNextImage, 500);
}
else {
$img.remove();
}
}
function startTimer() {
setInterval(displayNextImage, 500);
}
</script>
</head>
</html>
<body onload = "startTimer()">
<img id="img" src="image1.jpg">
</body>
</html>
Is there a way to get this to work in HTML only? I tried doing this, but it only stays on the first image:
<html>
<head>
<title>switch</title>
</head>
<body>
<img id="img" src="http://www.almightydad.com/wp-content/uploads/2010/10/testing-testing-123.jpg"
alt="" />
<script>
var images = [], x = 0;
images[0] = "http://www.almightydad.com/wp-content/uploads/2010/10/testing-testing-123.jpg";
images[1] = "http://trainwithfinishers.com/wp-content/uploads/2014/08/TEST.jpg";
function displayNextImage() {
if (++x < images.length) {
document.getElementById("img").src = images[x];
setInterval(displayNextImage, 500);
}
else{
img.remove();
}
function startTimer() {
setInterval(displayNextImage, 500);
}
</script>
</body>
</html>
Also, jQuery doesn't work on the site i'm using.
You never actually call the startTimer function.
Try adding startTimer(); before the script tag is closed.
Your first code had an onload event on the body, which would execute your function.
UPDATE (you're also missing a curly bracket on your if statement in displayNextImage())
<script type="text/javascript">
var images = [], x = 0;
images[0] = "http://www.almightydad.com/wp-content/uploads/2010/10/testing-testing-123.jpg";
images[1] = "http://trainwithfinishers.com/wp-content/uploads/2014/08/TEST.jpg";
function displayNextImage() {
if (++x < images.length) {
document.getElementById("img").src = images[x];
setInterval(displayNextImage, 500);
} else {
img.remove();
}
}
function startTimer() {
setInterval(displayNextImage, 500);
}
startTimer();
</script>
You just need to invoke the startTimer() function.
Read about JavaScript Function Invocation.
Also note that you missed closing the displayNextImage() function.
Replace your <script> code block with this one:
<script>
var images = [], x = 0;
images[0] = "http://www.almightydad.com/wp-content/uploads/2010/10/testing-testing-123.jpg";
images[1] = "http://trainwithfinishers.com/wp-content/uploads/2014/08/TEST.jpg";
function displayNextImage() {
if (++x < images.length) {
document.getElementById("img").src = images[x];
setInterval(displayNextImage, 500);
}
else{
img.remove();
}
}
function startTimer() {
setInterval(displayNextImage, 500);
}
startTimer();
</script>
Here is the working code snippet:
var images = [], x = 0;
images[0] = "http://www.almightydad.com/wp-content/uploads/2010/10/testing-testing-123.jpg";
images[1] = "http://trainwithfinishers.com/wp-content/uploads/2014/08/TEST.jpg";
function displayNextImage() {
if (++x < images.length) {
document.getElementById("img").src = images[x];
setInterval(displayNextImage, 500);
}
else{
img.remove();
}
}
function startTimer() {
setInterval(displayNextImage, 500);
}
startTimer();
<img id="img" src="http://www.almightydad.com/wp-content/uploads/2010/10/testing-testing-123.jpg"
alt="" />

Image change onclick using javascript is very fast?

Html and Javascript code:
<img src="imgs/right.gif" id="image_change" onclick="changeImage()"/>
<script>
function changeImage() {
var src = document.getElementById("image_change").src;
var imgsrc = src.substring(src.lastIndexOf("/")+1);
if (imgsrc == "left.gif")
{
document.getElementById("image_change").src = "imgs/right.gif";
alert('if'+document.getElementById("image_change").src);
}
else
{
document.getElementById("image_change").src = "imgs/left.gif";
alert('else'+document.getElementById("image_change").src);
}
}
</script>
When i click on the image, a new image is replacing in fraction of milli seconds..can i make the replacing of the image slow by using javascript or by adding any css class to it??any help would be appreciated..
try this
Using javascript
var op = 0.1; // initial opacity
element.style.display = 'block';
var timer = setInterval(function () {
if (op >= 1){
clearInterval(timer);
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op += op * 0.1;
alert("here");
}, 10);
var img =document.getElementById("image_change");
fade(img);// Chnage image in fade method
Using jquery
// increase the 500 to larger values to increase the duration
// of the fadeout and/or fadein
$('#image_change').fadeOut(500, function () {
$('#image_change').attr("src", "/newImage.png");
$('#image_change').fadeIn(500);
});
The above jQuery way is straight forward and easy , if you want this in vanilla JavaScript you can use setTimeout with opacity to create fade out and fade in effect for further details check link below
Pure JavaScript fade in function
You can use setTimeout() function of window object to make delay for execution of your code.
Try this :
HTML :
<img src="http://www.hdwallpapers-3d.com/wp-content/uploads/2014/03/Cartoon-6.jpg" id="image_change" onclick="changeImage();" />
javaScript :
function changeImage() {
var src = document.getElementById("image_change").src;
var imgsrc = src.substring(src.lastIndexOf("/") + 1);
if (imgsrc == "Cartoon-6.jpg")
{
window.setTimeout(function(){
document.getElementById("image_change").src = "http://topwallpaperswide.com/wp-content/uploads/cartoon-wallpapers-jerry-the-mouse-running-and-shouting-20140823213658-53f9097a18af8.jpg";
//alert('if'+document.getElementById("image_change").src);
}, 1000);
}
else
{
window.setTimeout(function(){
document.getElementById("image_change").src = "http://www.hdwallpapers-3d.com/wp-content/uploads/2014/03/Cartoon-6.jpg";
//alert('else'+document.getElementById("image_change").src);
}, 1000);
}
}
jsFiddle
You can do it this way:
function changeImage() {
setTimeout(function() {
var src = document.getElementById("image_change").src;
if (src == "http://s25.postimg.org/iyly1k3uz/arrow_left.png") {
document.getElementById("image_change").src = "http://s25.postimg.org/tzh36kw3v/arrow_right.png";
} else {
document.getElementById("image_change").src = "http://s25.postimg.org/iyly1k3uz/arrow_left.png";
}
}, 1000);
}
body {
background-color: lightblue;
}
<img src="http://s25.postimg.org/tzh36kw3v/arrow_right.png" id="image_change" onclick="changeImage()" />

8 image change on mouse hover and return to default when left

i have an 8 img elements in my page -
<img onmouseover="mousehover(this)" onmouseout="defaultImg(this)" src = "images/1_1.jpg" height="96" width="156" style="margin-right:12px;"/>
<img onmouseover="mousehover(this)" onmouseout="defaultImg(this)" src = "images/2_1.jpg" height="96" width="156" style="margin-right:12px;"/>
On hover it should change from 1_1 to 1_2 till 1_8 and then 1_1 again. On mouse out it should show the default pic i.e 1_1. Like this i have 2_1, 3_1 till 8_1.
The javascript function for mousehover is -
function mousehover(x){
for(var i=2; i<9; i++){
x.src = x.src.replace('images/rotator/1_' + i + '.jpg');
}
}
function defaultImg(x){
x.src = x.src.replace("images/rotator/1_1.jpg");
}
Somehow this mouse hover func does not work. And how do i get the defaultImg for all the images on mouse out. I am stuck here. Any ideas?
Try the following.Should work:
var timer;
var i=2;
function mousehover(x){
x.src = 'images/rotator/1_' + i + '.jpg';
i++;
timer = setTimeout(function(){mousehover(x)},2000);
}
function defaultImg(x){
i=2;
clearTimeout(timer);
x.src = "images/rotator/1_1.jpg";
}
You can pass the first number as parameter in the function calls.
<img onmouseover="mousehover(this, 1)" onmouseout="defaultImg(this, 1)" src = "images/1_1.jpg" height="96" width="156" style="margin-right:12px;"/>
<img onmouseover="mousehover(this, 2)" onmouseout="defaultImg(this, 2)" src = "images/2_1.jpg" height="96" width="156" style="margin-right:12px;"/>
And the JavaScript would be:
var interval;
function mousehover(x, y) {
var i = 1;
interval = setInterval(function() {
i++;
if (i > 8) {
clearInterval(interval);
i = 1;
}
x.src = 'images/rotator/' + y + '_' + i + '.jpg';
}, 500);
}
function defaultImg(x, y) {
clearInterval(interval);
x.src = 'images/rotator/' + y + '_1.jpg';
}
For more performance, I would combine all images into one big sprite, and play with the background-position instead of loading a new image each time.
Something in these lines should work:
var element = document.querySelector("#switch");
element.addEventListener('mouseover', function() {
this.src = "http://placehold.it/400x300";
});
element.addEventListener('mouseout', function() {
this.src = "http://placehold.it/200x300";
});
Fiddle
You need something like this:
//TIP: Insert listeners with javascript, NOT html
x.addEventListener('mouseover', function () {
var count = 1,
that = this,
timer;
timer = setInterval(function () {
if (count < 8) {
count++;
} else {
count = 1;
}
that.src = 'images/rotator/1_' + count + '.jpg';
}, 500);
function onMouseOut() {
that.src = 'images/rotator/1_1.jpg';
that.removeEventListener('mouseout', onMouseOut)
}
this.addEventListener('mouseout', onMouseOut);
});

Javascript changing an image within a div after a certain amount of time

I am currently making a web page with an image inside of a div tag. I wrote a script to change the image after a certain amount of time, and it works fine when I test the script alone, however; when I attempt to place the script within my web page, it does not change the image.
Here is the code for my script:
<!DOCTYPE html>
<html>
<body>
<script>
images = new Array;
images[0] = "img2.gif";
images[1] = "img3.gif";
images[2] = "img4.gif";
images[3] = "img5.gif";
images[4] = "img6.gif";
images[5] = "img7.gif";
images[6] = "img8.gif";
images[7] = "img9.gif";
images[8] = "img10.gif";
setInterval( function() {
changeImage()
}, 5000);
x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
if ( x < 8 ) {
x += 1;
} else if ( x = 9 ) {
x = 0;
}
}
</script>
<img id='ad' src="img.gif">
</body>
</html>
I have tested this script with the image inside of a div tag and it still works fine. When I put the same code into my web page, it does not work. Also note, the image file names are just examples. The images I am using are from photobucket, so I have very little control over what they are called. Any help I could get on this would be greatly appreciated.
You need to put your code inside window.onload = function() {}
var images = new Array();
images[0] = "img2.gif";
images[1] = "img3.gif";
images[2] = "img4.gif";
images[3] = "img5.gif";
images[4] = "img6.gif";
images[5] = "img7.gif";
images[6] = "img8.gif";
images[7] = "img9.gif";
images[8] = "img10.gif";
function changeImage() {
document.getElementById('ad').src = images[x];
if (x<8) {
x+=1;
}
else if (x===9) {
x=0;
}
}
window.onload = function() {
var x = 0;
setInterval(function() {
changeImage()
},5000);
}
Edit
This code has been tested on my local machine and works.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var images = new Array();
for (var i = 2; i < 11; i++) {
images.push("img" + i + ".gif");
}
var x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
document.getElementById('imgsrc').innerHTML = "<h1>" + images[x] + "</h1>";
if (x < 8) {
x += 1;
} else {
x = 0;
}
}
window.onload = function() {
setInterval(function () {
changeImage();
}, 1000);
}
</script>
</head>
<body>
<img id="ad" src="img.gif" />
<div id="imgsrc"><h1>img.gif</h1></div>
</body>
</html>
Here is a fiddle of the final code working. JSFiddle doesn't like window.onload for some reason, so I had to exclude it. This doesn't really demonstrate my point, but I thought I'd just include it anyway.
Your code works to change the image src in this fiddle: http://jsfiddle.net/snB2a/1/
Try to rename your variables images and x to longer names. What can happen is, if some other code in your page, or worse, some code in one of the script file you page references, use variable "x" without declare it locally, then it would actually modify your "x" variable.
Here is an example to demonstrate the problem:
function something()
{
for (x = 0; i < 10; x++)
dosomethingelse();
}
If the above function is called in your page, then it will overwrite your "x" variable. The following code is safe:
function something()
{
var x;
for (x = 0; i < 10; x++)
dosomethingelse();
}

Image change every 30 seconds - loop

I would like to make an image change after 30 seconds. The javascript I'm using looks like this:
var images = new Array();
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);
var x = 0;
function changeImage() {
document.getElementById("img").src=images[x];
x++;
}
HTML:
<img id="img" src="startpicture.jpg">
Now I haven't tested this one yet, but if my calculations are correct it will work :)
Now what I also want is to make a "fading transition" and I would like the changing of images to loop (it restarts after all the images have been shown).
Do any of you guys know how to do that?
I agree with using frameworks for things like this, just because its easier. I hacked this up real quick, just fades an image out and then switches, also will not work in older versions of IE. But as you can see the code for the actual fade is much longer than the JQuery implementation posted by KARASZI István.
function changeImage() {
var img = document.getElementById("img");
img.src = images[x];
x++;
if(x >= images.length) {
x = 0;
}
fadeImg(img, 100, true);
setTimeout("changeImage()", 30000);
}
function fadeImg(el, val, fade) {
if(fade === true) {
val--;
} else {
val ++;
}
if(val > 0 && val < 100) {
el.style.opacity = val / 100;
setTimeout(function(){ fadeImg(el, val, fade); }, 10);
}
}
var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);
You should take a look at various javascript libraries, they should be able to help you out:
mootools
jQuery
Dojo Toolkit
prototype
All of them have tutorials, and fade in/fade out is a basic usage.
For e.g. in jQuery:
var $img = $("img"), i = 0, speed = 200;
window.setInterval(function() {
$img.fadeOut(speed, function() {
$img.attr("src", images[(++i % images.length)]);
$img.fadeIn(speed);
});
}, 30000);
setInterval function is the one that has to be used.
Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.
CODE:
var im = document.getElementById("img");
var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;
function changeImage()
{
im.setAttribute("src", images[index]);
index++;
if(index >= images.length)
{
index=0;
}
}
setInterval(changeImage, 30000);
Just use That.Its Easy.
<script language="javascript" type="text/javascript">
var images = new Array()
images[0] = "img1.jpg";
images[1] = "img2.jpg";
images[2] = "img3.jpg";
setInterval("changeImage()", 30000);
var x=0;
function changeImage()
{
document.getElementById("img").src=images[x]
x++;
if (images.length == x)
{
x = 0;
}
}
</script>
And in Body Write this Code:-
<img id="img" src="imgstart.jpg">

Categories

Resources