Chuck's Academy

Basic HTML

Integration of HTML with JavaScript

Adding JavaScript to HTML

JavaScript is a programming language that allows you to add interactivity to web pages. You can insert JavaScript directly into HTML using the <script> tag. This tag can be placed inside <head> or <body>, depending on when you want the script to run.

html
"This JavaScript script displays a welcome message to the user using the alert function. The script tag allows you to include JavaScript code in the page."

Script Location: <head> vs <body>

The location of <script> in the document affects when the JavaScript code is executed. Placing the script in <head> executes the code before the page loads, while putting it at the end of <body> allows the JavaScript code to run after all the HTML is loaded.

html
"Here are two scripts, one in the head and one at the end of the body. The first one runs at the start, while the second runs after the page content has loaded."

Inline, Internal, and External Scripts

JavaScript can be added directly inline with HTML events, internally within <script> tags, or externally via linked .js files. Separating JavaScript into external files is ideal for keeping code organized.

html
"This example shows three ways to add JavaScript. An inline script, which is directly in the HTML, an internal script in the script tag, and an external script file linked with src."

DOM Elements and Selectors

The DOM (Document Object Model) represents the HTML structure as a tree of nodes, allowing JavaScript to interact with and modify the page. Selectors make accessing DOM elements easy. You can use methods like getElementById or querySelector.

html
"Here, we select a div by its id using getElementById. Then, we change its text content with textContent, allowing JavaScript to modify the page."

Chapter Closure

You have learned how to integrate JavaScript into your HTML pages, controlling when and where it runs. In the next chapter, we'll use this knowledge to build a practical project of a complete website with HTML.


Ask me anything