In this chapter we looked in more detail at the Date object, particularly with respect to world time and local time. We also looked at how to create timers to trigger code on a web page.
Create a web page with an advertisement image at the top. When the page loads, select a random image for that advertisement. Every four seconds, make the advertisement change to a different image making sure a different advertisement is selected until all the advertisement images have been seen.
This solution is based on the example in the chapter, Adverts.htm, where we displayed three images at set intervals one after the other. The first difference is that we select a random image each time, rather than the images in sequence. Secondly, we make sure we don't select the same image twice in one sequence by having an array, imagesSelected, with each element of that array being true or false depending on whether the image has been selected before. Once we've shown each image, we reset the array and start the sequence of selecting images randomly again.
The final difference between this solution and the example in the chapter is that we set the timer going continuously with setInterval(). So, until the user moves to another page our random display of images will continue.
Save this as ch09_q2.htm.
The solution is surprisingly simple. We create a new Date object based on the date entered by the user. Then we get the day of the week using the Date object's getDay() method. This returns a number, but by defining an array of days of the week to match this number, we can use the value of getDay() as the index to our days array.
We also do some basic sanity checking to check that the user has entered numbers and that in the case of the date, it's between 1 and 31. We could have defined a select element as the method of getting the date and only having number from 1 to 31. Of course, for either way, we don't check whether invalid dates are entered (for example, the 31st of February). You might want to try this as an additional exercise.
Hint: To get the last day of the month, get the first day of the next month then subtract 1.