Flash Gordon
Flash Gordon

Reputation: 1

How to change the image on a webpage by the time of day using JavaScript

I've seen variations of this before but I keep running into roadblocks that are causing headaches.

What I want to do is change a banner image on my web page by the time of day in my region (Pacific Standard) by using JavaScript. I get the main idea that I have to do for the function, but I'm confused on how I can import an image or add an image into the webpage when it wasn't there before.

    function timeOfDayImage() {
    var now = new Date;
    var timeNow = now.getHours();

       if(timeNow < 8 || timeNow > 10){
            code
       }
       else {
          code
       }

Any help?

Upvotes: 0

Views: 361

Answers (3)

SomeShinyObject
SomeShinyObject

Reputation: 7811

Use an ID in your banner image like so:

<img id="banner" alt="Something appropriate" />

And then use getElementById to select the reference from the DoM. Change the source (src) attribute with the variable reference of the selected element. If you want, you can change the alt attribute also, to ensure that the changed image is descriptive for screen readers.

function timeOfDayImage() {
    var now = new Date;
    var timeNow = now.getHours();
    var img = document.getElementById("banner");
    if (timeNow < 8 || timeNow > 10) {
        img.src="someimage.png";
        img.alt="Something equally appropriate";
    } else {
        img.src="someimage.png";
        img.alt="Something appropriate here too";
    }
}

timeOfDayImage();

Fiddle with a non-existent image(proof of concept)

Upvotes: 0

Ejaz
Ejaz

Reputation: 8872

You don't need to import an image into the web page. Set the src attribute of the banner image to the URL of new image and the browser will load it for you

function timeOfDayImage() {
   var now = new Date;
   var timeNow = now.getHours();
   if(timeNow < 8 || timeNow > 10){
      document.getElementById('image').src='http://www.images.com/banner1.jpg';
   }
   else {
      document.getElementById('image').src='http://www.images.com/banner2.jpg';
   }
}

Upvotes: 0

Blender
Blender

Reputation: 298196

I'd give your body element a class:

function timeOfDayImage() {
    var now = new Date();
    var timeNow = now.getHours();

    if (timeNow < 8 || timeNow > 10) {
        body.classList.add('it-is-time');
    }
}

And change the element with CSS:

body #banner {
    background-image: url('images/one.png');
}

body.it-is-time #banner {
    background-image: url('images/two.png');
}

Upvotes: 1

Related Questions