Introduction
To get started programming with JavaScript, you first have to write few scripts. Now there are a few ways you can do this with HTML and Javascript.
- You can write your code in a separate file and then imports the code into your HTML. This is the preferred method in most situations.
- You can put your scripts inline with your HTML code. This works, but is messy and can cause some interesting issues if the scripts come before the elements the script is attempting to modify.
- You can put your code in functions in the head section of the HTML document. Then, specify a method to run when the document loads.
As you might guess, the examples on this site will use the last method. Its just a lot simpler show and provide the source for the examples if everything is in one file.
A Base JavaScript Example
Examples for this site use the basic structure shown below. Explanations of the code follow the example.
jsbase.html (Sample) (Source)
1:<html>
2: <head>
3: <title>JavaScript Base File</title>
4: <script type="text/javascript">
5: function main(){
6: /* Define and print array normal */
7: var myStr = "<p>Hello World!</p>";
8: var div1 = document.getElementById("div1");
9: div1.innerHTML = myStr;
10:
11: }
12: </script>
13: </head>
14:<body onLoad="main()">
15: <h2>JavaScript Base File</h2>
16: <h4>Example Output</h4>
17: <div id="div1">
18: </div>
19:</body>
20:</html>
Here are some of the key points.
- Line 4 - The script tag is used to hold JavaScript code.
- Line 5 - A function is setup to be the main execution point for the script. The name could be anything, but main seems like a good choice.
- Line 7 - Our first variable is defined. Its a string and the value is set to an HTML p tag.
- Line 8 - Basically, this line tells the browser to find an element with an
id
attribute set to "div1". Save this this element to a variable so it can be used again. In this case, the attribute identifies adiv
tag. - Line 9 - Each element in an HTML document has a property of
innerHTML
. By assigning a value to the property, you can overwrite the contents of the element. In this example, we are pointing to an emptydiv
element. The assignment set the contents of thediv
tag to the string created 2 lines earlier. - Line 14 - The
onLoad
attribute tells the browser to execute a piece of code once the document is loaded into memory. In this case, the main function is called.
If you click on the link and look at the source file. You will see that the hello message is inserted into the HTML document. With this basic setup, you can explore many of the features of JavaScript in a browser.