12. Incorporating JavaScript code into HTML pages.
Incorporating JavaScript code into HTML pages involves placing the
JavaScript code within <script> tags in the HTML document.
1. Inline JavaScript: You can include JavaScript code directly within the
HTML file using the <script> tags. Place the <script> tags either within the
<head> section or just before the closing </body> tag.
Here's an example:
<!DOCTYPE html>
<html>
<head>
<title>My HTML Page</title>
<script>
// Inline JavaScript code
function myFunction() {
// Code here
}
</script>
</head>
<body>
<!-- HTML content
<button onclick="myFunction()">Click me</button>
</body>
</html>
2. External JavaScript file: Alternatively, you can create a separate
JavaScript file with a .js extension and include it in the HTML document
using the <script> tag's src attribute. This allows for better code
organization and reusability.
Here's an example:
<!DOCTYPE html>
<html>
<head>
<title>My HTML Page</title>
<script src ="script.js"></script>
</head>
<body>
<!-- HTML content
<button onclick="myFunction()">Click me</button>
</body>
</html>
In the external JavaScript file (script.js in this case), you can define
functions, variables, and interact with the DOM.
Handling events and interacting with the DOM:
JavaScript allows you to handle events triggered by user interactions or other
actions and manipulate the Document Object Model (DOM) to dynamically
update the web page.
Here's an example:
// script.js
function myFunction() {
// Event handler for the button click
var element = document.getElementById("myElement");
element.innerHTML = "Button clicked!";
}
// Changing the content dynamically
var element = document.getElementById("myElement");
element.innerHTML = "Initial content";
<!-- index.html
<!DOCTYPE html>
<html>
<head>
<title>My HTML Page</title>
<script src="script.js"></script>
</head>
<body>
<!-- HTML content -->
<div id="myElement">Initial content</div>
<button onclick="myFunction()">Click me</button>
</body>
</html>
In this example, when the button is clicked, the myFunction() event handler
is triggered. It locates the element with the ID "myElement" and changes its
content to "Button clicked!".
JavaScript provides numerous event types, such as click, mouseover,
keydown, etc., which can be used to handle various user interactions. The
DOM API allows you to access and manipulate HTML elements, modify
their attributes, add or remove elements dynamically, and update their
content.
By combining JavaScript with HTML, you can create interactive web pages
that respond to user actions, update content dynamically, and provide a rich
user experience