How to use JS in HTML


JavaScript (JS) is a powerful scripting language used to create dynamic and interactive content on web pages. When combined with HTML and CSS, JavaScript enables web developers to enhance the functionality and interactivity of a website. There are several ways to include JavaScript in an HTML document, each serving different purposes.

1. Inline JavaScript

Inline JavaScript is written directly within an HTML element using the onclick, onchange, or other event handler attributes. This method is often used for simple actions that need to be triggered by user interaction.

Example

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Inline JavaScript Example</title> </head> <body> <h1>Welcome to My Website</h1> <button onclick="alert('Button clicked!')">Click Me</button> </body> </html>

2. Internal JavaScript

Internal JavaScript is written within a <script> tag in the <head> or <body> section of the HTML document. This method is useful for embedding JavaScript that applies to a single page.

Example

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Internal JavaScript Example</title> <script> function showMessage() { alert('Hello, welcome to my website!'); } </script> </head> <body> <h1>Welcome to My Website</h1> <button onclick="showMessage()">Click Me</button> </body> </html>

3. External JavaScript

External JavaScript is stored in a separate .js file and linked to the HTML document using the <script> tag. This method is preferred for larger projects or when you want to reuse the same JavaScript code across multiple pages.

Example

1. Create a JavaScript file (script.js):

// script.js function showMessage() { alert('Hello, welcome to my website!'); }

2. Link the JavaScript file in the HTML document:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>External JavaScript Example</title> <script src="script.js"></script> </head> <body> <h1>Welcome to My Website</h1> <button onclick="showMessage()">Click Me</button> </body> </html>

4. Async and Defer Attributes

When using external JavaScript, the <script> tag can include async and defer attributes to control the loading and execution of the script.

  • async: The script is downloaded and executed asynchronously as soon as it's available, without blocking the rendering of the page.

    Example:

    <script src="script.js" async></script>
  • defer: The script is downloaded asynchronously, but its execution is deferred until the entire HTML document is parsed. This ensures that the script runs only after the page content is fully loaded.

    Example:

    <script src="script.js" defer></script>

5. JavaScript in the Body Section

JavaScript can also be placed at the end of the <body> section. This method ensures that the HTML content is fully loaded before the script runs, which can improve page load performance.

Example

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript at the End of Body</title> </head> <body> <h1>Welcome to My Website</h1> <button onclick="showMessage()">Click Me</button> <script> function showMessage() { alert('Hello, welcome to my website!'); } </script> </body> </html>

6. DOM Manipulation

JavaScript is often used to manipulate the Document Object Model (DOM) of an HTML page. This allows for dynamic changes to the content and structure of the web page after it has been loaded.

Example

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>DOM Manipulation Example</title> <script> function changeContent() { document.getElementById("myParagraph").innerText = "Content has been changed!"; } </script> </head> <body> <h1>Welcome to My Website</h1> <p id="myParagraph">This is the original content.</p> <button onclick="changeContent()">Change Content</button> </body> </html>

7. Event Listeners

JavaScript can also add event listeners to HTML elements to respond to user interactions without using inline event handlers.

Example

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Event Listener Example</title> <script> document.addEventListener("DOMContentLoaded", function() { document.getElementById("myButton").addEventListener("click", function() { alert("Button clicked!"); }); }); </script> </head> <body> <h1>Welcome to My Website</h1> <button id="myButton">Click Me</button> </body> </html>

Best Practices

  1. Keep JavaScript Separate: Use external JavaScript files to keep your HTML clean and your scripts reusable.
  2. Use defer or Place Scripts at the End: Improve page load performance by using the defer attribute or placing scripts at the end of the <body> section.
  3. Avoid Inline JavaScript: Inline scripts can clutter your HTML and are harder to maintain. Use event listeners instead.
  4. Write Clean, Commented Code: Always comment your JavaScript code for better readability and maintainability.