Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change background on every 5s

I have image background.jpg as the background. Every 10s, how to load a new background background_n.jpg which stays for 100ms and then back to background.jpg and so on?

like image 658
Danka Avatar asked Jun 22 '11 13:06

Danka


People also ask

How to change background image in HTML every 5 seconds?

How do I make an image change in HTML? Change setTimeout(“changeImage()”, 30000); to setInterval(“changeImage()”, 30000); and remove var timerid = setInterval(changeImage, 30000); .

How can I have an image that changes every 5 seconds in react js?

Set an intervall that executes every 5 seconds in a useEffect that sets the new state with a randomly picked image.

How do I change the background image after a certain time in HTML?

The URL of the Images will be stored in a JavaScript Array and then using JavaScript setInterval function, the Background Image of HTML DIV will be dynamically changed (swapped) every 5 seconds using jQuery. The following HTML Markup consists of an HTML DIV element.


4 Answers

Here is an example (that does not need jQuery to work) :

var rotate = false;
function setbackground(){
  window.setTimeout( "setbackground()", 5000);
  newImage = rotate ? 'url(pict1.jpg)' : 'url(pict2.jpg)';
  rotate = !rotate;
  document.getElementById('change').style.backgroundImage = newImage;
}
like image 87
JMax Avatar answered Oct 24 '22 12:10

JMax


function change_background( new_image_source ) {

  var myimage = $( '#myimage' );

  myimage.attr( 'src', new_image_source );

  setTimeout( function () {

    change_background( 'new image source here' );

  }, 10000);

}
like image 22
Jose Faeti Avatar answered Oct 24 '22 10:10

Jose Faeti


Use setInterval and setTimeout

window.setInterval(function(){    
   window.setTimeout(function(){
       $('div').css('background-image','url(background.jpg)');
   },100);
    $('div').css('background-image','url(background_n.jpg)');
},10000);

example: http://jsfiddle.net/niklasvh/M56A6/

like image 3
Niklas Avatar answered Oct 24 '22 10:10

Niklas


  • You can use setTimeout(function, timeout) (plain Javascript function) to set a function (which you can define) to run after timeout milliseconds

    For example (the alert will be displayed after 10 seconds):

    setTimeout(function () {
         alert('I am running!');
    }, 10000);
    
  • You can change an element's background with:

    $(element).css('background-image', 'url(xy.jpg)')
    
  • Make sure you preload you background images before using them.

  • I'd advise against using setInterval() for this (for such small intervals, it could stack up), use a chain of setTimeout()s to set up the repeating action.

like image 2
kapa Avatar answered Oct 24 '22 11:10

kapa