HTML
๐ HTML and JavaScript
๐น 1. What is a Script in HTML?
JavaScript is used to make web pages interactive and dynamic.
- The
<script>tag is used to add JavaScript code directly into HTML or to link an external JS file. - The
<noscript>tag is used to add JavaScript code directly into HTML or to link an external JS file.
๐น 2. Using the <script> Tag
2.1 Writing JavaScript Inside HTML
HTML
<script>
console.log("Hello!");
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
Here, the JavaScript code is written directly inside the <script> tag and runs when the page loads.
2.2 Linking an External JavaScript File
HTML
<script src="app.js"></script>
- The src attribute specifies the URL of the JavaScript file.
- This method is better for long scripts or code used on multiple pages.
๐น 3. What Can You Do with JavaScript?
3.1 Changing HTML Content
HTML
document.getElementById("demo").innerHTML = "Hello JavaScript!";
- Changes the text inside the HTML element with id="demo".id="demo".
3.2 Changing CSS Styles
HTML
document.getElementById("demo").style.fontSize = "25px";
document.getElementById("demo").style.color = "red";
document.getElementById("demo").style.backgroundColor = "yellow";
- Dynamically changes the appearance of an element.
3.3 Changing HTML Attributes
HTML
document.getElementById("image").src = "picture.gif";
- Changes the src attribute of an
<img>tag to display a new image.
๐น 4. Using <noscript>
HTML
<noscript>
Sorry, your browser does not support JavaScript!
</noscript>
- If the browser does not support JavaScript, the message inside
<noscript>is displayed. - This prevents the page from being completely non-functional.
๐น 5. Full Example โ Dynamic Page with JavaScript
HTML
<!DOCTYPE html>
<html lang="en">
<head>;
<meta charset="UTF-8">
<title>Script Example</title>
</head>
<body>
<h1 id="demo">Initial Text</h1>
<img id="image" src="firstimage.jpg" alt="Image">
<script>
// Runs when the page loads
document.getElementById("demo").innerHTML = "Hello, JavaScript is running!";
document.getElementById("demo").style.color = "blue";
document.getElementById("image").src = "changedimage.png";
</script>
<noscript>
JavaScript is disabled or not supported. Some features may not work.
</noscript>
</body>
</html>
๐น 6. Explanation
- The
<script>tag executes JavaScript code when the page loads. - The code can change the
<h1>text and update its style. - The image source can be dynamically updated.
- The
<noscript>tag informs users when JavaScript is not supported.
๐น 7. Why is it Important?
- JavaScript makes web pages live and interactive.
- The
<script>tag allows you to add logic, animations, user interactions, and API connections to a page. - The
<noscript>tag provides alternative content for users without JavaScript support.
