0

I need some sort of script to display diffrent content depending on the day of the week, mainly images. This is what I've tried

<script>
    function myFunction() {
        var d = new Date();
        var weekday=new Array(7);
        weekday[0]="Sunday";
        weekday[1]="Monday";
        weekday[2]="img src="http://totalscript.ro/logo.png";
        weekday[3]="Wednesday";
        weekday[4]="Thursday";
        weekday[5]="Friday";
        weekday[6]="Saturday";

        var x = document.getElementById("demo");
        x.innerHTML=weekday[d.getDay()];
    }
</script>

I want to make this able to display images. Can you help?

talemyn
  • 7,822
  • 4
  • 31
  • 52

2 Answers2

1

You can do the following:

var images = [
    'http://my.site.com/img1.jpg',
    'http://my.site.com/img2.jpg',
    'http://my.site.com/img3.jpg',
    'http://my.site.com/img4.jpg',
    'http://my.site.com/img5.jpg',
    'http://my.site.com/img6.jpg',
    'http://my.site.com/img7.jpg',
];

function placeImage(id, images) {
    document.getElementById(id).innerHTML = [
        '<img src="',
        images[(new Date()).getDay()],
        '"/>'
    ].join('');
}

placeImage('demo', images);

Some Enhancements

  • Placing array of image sources outside the function will prevent recreation of array each time function is called
  • Using function parameters make it more generic and allow to populate for example another image container or take images from another source
  • [...].join('') is kind of string buffer that for old browsers may provide better performance
Vadim
  • 8,701
  • 4
  • 43
  • 50
0

Not sure if you are just looking at how to assign an image to an item in JQuery? If that is it

$("#demo").attr("src","http://imageLocation");

or if you want to use your already created variable, which is using raw javascript:

x.attr("src","http://imageLocation");
gcoleman0828
  • 1,541
  • 3
  • 30
  • 49