HTML Priorities: Understanding HTML Behavior
The HTML behavior tutorial demonstrates how you can use JavaScript methods within HTML code.
Warm-up
Become familiar with HTML priorities by learning about:
-
Using JavaScript Code within HTML
Learn how to format and place JavaScript code within HTML code.
Using JavaScript Code within HTML
To provide users with JavaScript-based features, you must learn to use JavaScript code within an HTML document:
- To use JavaScript code in the <head> element, place the relevant JavaScript content in a <script> tag:
<head> <script src="js/jquery_1.9.0_min.js"></script> <script> window.onload = function() { testLog('head onload'); }; $(document).ready(function() { testLog('head ready'); }); </script> </head>
The JavaScript code within the <head> element is sent to Interpreter. As there are no methods to be handled immediately, its execution is suspended.
- To use JavaScript code in the <body> element, place the relevant JavaScript content in a <script> tag:
<body> <script src="js/jquery_1.9.0_min.js"></script> <script> function testLog(txt) { var logText = document.querySelector('.log'); logText.innerHTML += '<li>JavaScript in HTML ' + txt + '</li>'; }; window.onload = function() { testLog('body onload'); }; $(document).ready(function() { testLog('body ready'); }); testLog('body'); (function() { testLog('body anonymous function'); }(); </script> </body>
The JavaScript code within the <body> element is sent to Interpreter. The anonymous method is immediately executed, and the HTML DOM structure is set up. The methods in the $(document).ready method and in the onload event are executed in the stored order.
Note |
---|
jQuery has to be called from both the <head> and <body> elements. The logText variable has to be called from the <body> element. The method connected to the onload event in the <head> element is not executed. |