Write a comment on this article
Get ready for your first function with JavaScript. Open a simple text-editor like Notepad on Microsoft Windows and you are ready to begin.
As you know from the introduction there are two ways to deliver your JavaScript code. Either within an HTML file or in a seperate file which is linked in an HTML file. We choose the first option, so we will have to create one file only.
First, we create a valid HTML file with a simple head and body containing just a paragraph with a button to call our JavaScript function and a block element to show the result of the function. If you are not familiar with HTML yet, check the introduction to HTML. Copy the following code to your editor and save the file as "My_first_JavaScript_function.html". It's important that the file ending is html, so your browser will open it.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My first JavaScript function</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<p><button name="callJS">Get current time</button></p>
<div id="output"></div>
</body>
</html>
This is just the basic HTML structure and has no JavaScript in it yet. But you can open it right now to test it, your browser should display a button with the label "Get current time".
As the label of the button already tells, we want it to display the current time. Not once, but every time it is clicked. Now we add a JavaScript function. Functions should be declared in the head of a document. The code itself must be inside a special element, the <script> element. So we first create a new element:
<script type="text/javascript">
<!--
/* JAVASCRIPT GOES HERE */
// -->
</script>
As you can see, there is an HTML comment inside the element. This prevents older browsers from displaying the code. The JavaScript function is inserted between the tags of the HTML comment.
To declare a new function in JavaScript, we use the keyword "function". We call our function "getCurrentTime", and it will do what it says.
function getCurrentTime(){
/* do something */
}
Inside the function we want to do the following steps:
First step: get the current time. JavaScript has a built-in prototype "Date". When it is initialized it contains the current date and time (of the client's operating system of course, because JavaScript runs inside the browser and the browser gets the date from the operating system it's running in). So we create a new Date-object and store it in a variable called "now":
var now = new Date();
We can now use the prototype's methods to get the hours, minutes and seconds from our date-object. We will need the following three methods: getHours, getMinutes and getSeconds. Each value we will hold in a seperate variable with a adequate name:
var hours = now.getHours(); var minutes = now.getMinutes(); var seconds = now.getSeconds();
Step two: format the time. One big advantage in JavaScript is that variables can change their data types. Depending on the value you are assigning to a variable, it gets the proper data type. So we have our three variables, all of them are of type "Number". When we output the time, we want to prefix a "0" to those numbers which are less than ten. So, we check each variable with an if-statement:
if(hours<10){
hours = "0"+hours;
}
if(minutes<10){
minutes = "0"+minutes;
}
if(seconds<10){
seconds = "0"+seconds;
}
Step three: write the time to the block element "output". JavaScript allows the modification of the document through the Document Object Model (DOM). One important object is the "document" which represents the body of a webpage and offers several methods to add, modify and remove elements. The method getElementById returns a pointer to a specific element. This can be any element which has an attribute "id".
We created a div-element with the id "output". Using the method described above, we can fetch this element and change its content by setting the attribute "innerHTML". As value we use a string combined of text and our time variables:
var output = document.getElementById("output");
output.innerHTML = "Current time: "+hours+":"+minutes+":"+seconds;
We are nearly done. What we have to do now is tell the button to call our function when it is clicked. For this we use the attribute "onclick":
onclick="getCurrentTime();"
That's it. A simple function returning the date when a button is clicked. You can try this example here: My_first_JavaScript_function.html. And here is the complete source code. Copy it, paste it into your file, save your file and open it with your browser.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My first JavaScript function</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
<!--
function getCurrentTime(){
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
if(hours<10){
hours = "0"+hours;
}
if(minutes<10){
minutes = "0"+minutes;
}
if(seconds<10){
seconds = "0"+seconds;
}
var output = document.getElementById("output");
output.innerHTML = "Current time: "+hours+":"+minutes+":"+seconds;
}
// -->
</script>
</head>
<body>
<p><button name="callJS" onclick="getCurrentTime();">Get current time</button></p>
<div id="output"></div>
</body>
</html>
Everytime you click the button the current time is displayed because the function "getCurrentTime" always creates a new Date object.
JavaScript, function
If you have a question or a problem and you're looking for a solution, please use the forum. Comments might not be answered.