Changing HTML Background Image Using JavaScript, depending on time of day (Using Multiple Images)? -
so i'm trying change background image of website correlate time of day.
ex. it's evening, background picture change sunset. it's morning, background picture sunrise.
but, wanting have function choose several arrays of pictures randomly. such as, have array of 3 evening, array 3 morning, array of 3 afternoon, etc. depending on time of day, function choose picture randomly correlating array , use picture background.
i don't know if it's possible, appreciate guidance.
edit:
//greeting based on time of day var today = new date(); var hournow = today.gethours(); var greeting; var style; if(hournow >= 18) { greeting = 'good evening.'; } else if (hournow >= 12) { greeting = 'good afternoon.'; } else if (hournow > 0) { greeting = 'good morning.'; } else { greeting = 'hello.'; } document.write('<h1>' + greeting + '</h1>');
there isn't of image arrays on there because don't know how type out array of images or document.get?.
thanks posting code.
take @ this, it's extension of code shows how solve problem. of course, it's intended give head start. surely isn't "production code", works :)
here's functioning code:
<!doctype html> <html> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript"> //greeting based on time of day var today = new date(); var hournow = today.gethours(); var greeting; var style; var timeofday; if(hournow >= 18) { timeofday = 1; } else if (hournow >= 12) { timeofday = 2; } else if (hournow > 0) { timeofday = 3; } else { timeofday = 0; } // randomize 3 images var rnd = math.floor(math.random() * (4 - 1) + 1); // returns random number between 1 (inclusive) , 4 (exclusive) switch (timeofday) { case 1: // evening greeting = 'good evening.'; switch (rnd) { case 1: document.write('<img src="eveningimage1.jpg" />'); break; case 2: document.write('<img src="eveningimage2.jpg" />'); break; case 3: document.write('<img src="eveningimage1.jpg" />'); break; } break; case 2: // afternoon greeting = 'good afternoon.'; switch (rnd) { case 1: document.write('<img src="afternoonimage1.jpg" />'); break; case 2: document.write('<img src="afternoonimage2.jpg" />'); break; case 3: document.write('<img src="afternoonimage1.jpg" />'); break; } break; case 0: // morning greeting = 'good morning.'; switch (rnd) { case 1: document.write('<img src="morningimage1.jpg" />'); break; case 2: document.write('<img src="morningimage2.jpg" />'); break; case 3: document.write('<img src="morningimage1.jpg" />'); break; } break; default: // generic greeting = 'hello.'; switch (rnd) { case 1: document.write('<img src="genericimage1.jpg" />'); break; case 2: document.write('<img src="genericimage2.jpg" />'); break; case 3: document.write('<img src="genericimage1.jpg" />'); break; } break; } document.write('<h1>' + greeting + '</h1>'); </script> <body> </body> </html>
i hope helps ;)
Comments
Post a Comment