Introduction
I discovered a cool little trick while source diving through Scott Mathson's web site. With just a couple lines of JavaScript you can create a message that displays a different greeting depending on the day of the week.
Create a Script with a Weekday Array
Create a <script>
tag with type
of text/javascript
. Define a variable called weekday
with a different greeting set to each index.
<script type="text/javascript">
var weekday = new Array(7)
weekday[0] = "spectacular Sunday"
weekday[1] = "marvelous Monday"
weekday[2] = "terrific Tuesday"
weekday[3] = "wonderful Wednesday"
weekday[4] = "totally cool Thursday"
weekday[5] = "fantastic Friday"
weekday[6] = "sweet Saturday"
</script>
Set Weekday Value to the Current Date
Also inside the script tag, create a variable called currentDate
set with the Date()
object and then set the current day to weekdayValue
.
var currentDate = new Date()
weekdayValue = currentDate.getDay()
Write to the Document
Use the Document.write() method to write a string of text to the document with paragraph tags containing the weekday value..
document.write(
'<p>Have a ' + weekday[weekdayValue] + '!</p>'
)
Noscript Fallback
Lastly, you'll want to include a <noscript>
tag in case the user has JavaScript turned off in their browser.
<noscript>
<p>Have a great day!</p>
</noscript>
Full Script
<script type="text/javascript">
var weekday = new Array(7)
weekday[0] = "spectacular Sunday"
weekday[1] = "marvelous Monday"
weekday[2] = "terrific Tuesday"
weekday[3] = "wonderful Wednesday"
weekday[4] = "totally cool Thursday"
weekday[5] = "fantastic Friday"
weekday[6] = "sweet Saturday"
var currentDate = new Date()
weekdayValue = currentDate.getDay()
document.write(
'<p>Have a ' + weekday[weekdayValue] + '!</p>'
)
</script>
<noscript>
<p>Have a great day!</p>
</noscript>
Top comments (4)
I appreciate the shout-out, Anthony! 😊
This is so fun!
Works great in joomla as long as you use code mirror editor.
Would it be possible to do this for every day of the year, and to make it a bunch of embedded YouTube videos as well? If so, how so? Thanks for a great post.