- 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.
Examples for this site use the basic structure shown below. Explanations of the code follow the example.
Here are some of the key points.
- 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
idattribute set to "div1". Save this this element to a variable so it can be used again. In this case, the attribute identifies a
- 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 empty
divelement. The assignment set the contents of the
divtag to the string created 2 lines earlier.
- Line 14 - The
onLoadattribute tells the browser to execute a piece of code once the document is loaded into memory. In this case, the main function is called.