How to Load JavaScript in DIV
There may be times when you need your JavaScript code to execute automatically without the need for the user to click on a button or link. You can do this using the Hypertext Markup Language or HTML standard "onload()" command for the "<body>" or "<img>" tags. The "onload()" command is not available for the "<div>" HTML tag, but you can accomplish the same feat by embedding the "<script>" tag immediately after the "<div>" with a reference to a JavaScript source file or a previously loaded JavaScript function.
Instructions
-
-
1
Click on the "Start" button. Click clicking on "All Programs." Click the "Accessories" menu option. Click "Notepad" to launch the text editor.
-
2
Type the following code into the text editor. Alternatively, select the code with the mouse, press " Control-c" then press " Control-v" to paste the code into the editor.
<html>
<body>
<div>
<script type="text/javascript" src="test.js"></script>
</div>
</body>
</html> -
-
3
Click the "File" menu item. Select the "Save" option. Save under the file name "test.html."
-
4
Click the "File" menu item. Click on the "New" menu item. Type the following code into the new text editor window. Alternatively, select the code with the mouse, press " Control-c" then press " Control-v" to paste the code into the editor.
function showit()
{
alert("Works!");
}
showit(); -
5
Click the "File" menu item. Select the "Save" option. Save under the file name "test.js" in the same directory as the "test.html" file.
-
6
Launch the web browser by clicking the "Start" button, clicking on "All Programs" and clicking on "Internet Explorer." Click on the "File" menu item and select "Open File."
-
7
Locate the file "test.html" just created, select it with the mouse then click on "Open."
You should see an alert box with the message, "Works!"
-
1
Tips & Warnings
Reuse the script you created above elsewhere in your HTML file by placing the line "<script onload='showit()' ></script>" where you want the code to execute. Since the function is already in memory, it will execute immediately.
Carefully review any code you did not write yourself before you embed it within your web page. Malicious hackers can create code that can call, retrieve and execute harmful JavaScript files saved on another server without your knowledge or consent. Avoid code that has been obfuscated or that contains links to any files located on outside servers unless you fully trust the source providing the code.
References
Resources
- Photo Credit Comstock/Comstock/Getty Images