Introduction
In this article, I will show you how to run a JavaScript code selectively. Sometimes the requirements are like we want to run a specific section of script on a specific day or at a specific time of the day. For example, let's consider the following situations:
- If you want to change the background of a website on some special days like Christmas.
- If you want a different look for your website at a specific time of the day.
In all of the preceding cases, this article will be very useful. So let's start our discussion by starting with the first example.
The Date Class
The Date object of JavaScript is very important to understand before we code the preceding situations. It is very big and it's not possible to cover it completely in this article.
We will discuss only those methods of this class that we will use in our script.
- getDate: Returns the day of the month (1-31) for the specified date depending on local time. It doesn't take any parameter.
- getDay: Returns the day of the week (0-6) for the specified date depending on local time. Always remember that count of days starts from 0 in JavaScript.
- getHours(): Returns the hour (0-23) on the specified date depending on local time. Always remember that the count of hours starts from 0.
- getMinutes(): Returns the minutes (0-59) on the specified date depending on local time. Always remember that the count of hours starts from 0.
- getMonth(): Returns the month (0-11) on the specified date depending on local time. Always remember that the count of hours starts from 0. So for December that is 12th month is represented by 11 in JavaScript.
- getSeconds(): Returns the seconds (0-59) on the specified date depending on local time.
Running script on special days
Use the following procedure to do it:
- First, we will detect the current date.
- Second, we will compare the current date with our goal day.
- Thirdly we will execute the script if the result of the second step is true.
Example
HTML
- <!DOCTYPE html>
- <html>
- <head>
- <linkhreflinkhref="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.min.css"rel="stylesheet"type="text/css"/>
- <scriptsrcscriptsrc="http://code.jquery.com/jquery-1.10.2.min.js"></script>
- <scriptsrcscriptsrc="http://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
- <metacharsetmetacharset=utf-8/>
- <title>JS Bin</title>
- </head>
- <body>
- <dividdivid="dlg"title="Congratulations"><p>Happy independence day!</p></div>
- </body>
- </html>
CSS




Comments
Join the conversation! Your thoughts help the community grow.