HTML and CSS Reference
In-Depth Information
Running JavaScript Commands as Hypertext Links
Another way to run a JavaScript command in response to an event is to treat it as a
hypertext link. This method is similar to running the command in response to a click
event within an element and employs the syntax
<a href=“javascript: script ”>content</a>
where script is the command (or commands) you want to run when a user clicks the
link. For example, the following code runs the calcTotal() function when a user clicks
the following link:
<a href=“javascript:calcTotal()”>
Calculate total cost
</a>
This technique was often used for older browsers that did not support event handlers,
or for elements that did not support the onclick event handler. This issue was more
prevalent when event handlers were a new feature of HTML and JavaScript. Now, run-
ning JavaScript commands through hypertext links is considered a bad practice because
it misuses the href attribute, which should be reserved for linked documents and not
commands. However, you might see this code still used in legacy pages.
Working with Date Objects
Now that you've created the initial form of the NYClock() function, you need to generate
the date and time information rather than typing the values directly into the JavaScript
code. To work with dates, JavaScript supports a Date object, which contains information
about a specified date and time. You create variables based on Date objects using the
following command:
variable = new Date(“ month day , year hours : minutes : seconds ”);
In this command, variable is the name of the variable that contains the Date
object, and month , day , year , hours , minutes , and seconds provide the date and
time values to be stored in the object. Time values are entered using 24-hour time;
for example, a time of 2:35 p.m. would be entered as 14:35. The following command
stores a Date object containing a date of February 24, 2015 and a time of 2:35:05 p.m.
in the thisDate variable:
thisDate = new Date(“February 24, 2015 14:35:05”);
If you omit the hours , minutes , and seconds values, JavaScript assumes that the
time is 0 hours, 0 minutes, and 0 seconds—in other words, midnight of the specified
day. If you omit both the date and time information, JavaScript returns the current date
and time, which it gets from the system clock on the user's computer. Thus, the following
command stores a Date object containing the current date and time in the thisDate
variable:
thisDate = new Date();
Search WWH ::




Custom Search