A Script, a compact program employed alongside HTML, enhances web pages by adding attractiveness, dynamism, and interactivity, like triggering an alert pop-up window upon a mouse click. Presently, the dominant scripting language for websites is JavaScript.
Example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Date and Time example</h1>
<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>
<p id="demo"></p>
</body>
</html>
Output:
HTML <script> Tag
The HTML <script> tag is used to specify a client-side script. It may be an internal or external JavaScript that contains scripting statements, hence we can place the <script> tag within the <body> or <head> section.
JavaScript is commonly utilized for image manipulation, validating forms, and dynamically altering content. To choose an HTML element, JavaScript employs the method document.getElementById.
Example
<!DOCTYPE html>
<html>
<body>
<h2>Use JavaScript to Change Text</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World";
</script>
</body>
</html>
Output:
HTML events with JavaScript
An event refers to an action performed by a user or a web browser, such as clicking a mouse or loading a page. These actions are instances of events, and JavaScript is utilized to trigger specific actions in response to these events.
HTML offers event handler attributes that can interact with JavaScript code to execute a specific action when an event occurs.
Syntax:
<element event = "JS code">
Example
document.getElementById("myBtn").addEventListener("click", () => {
alert("Hi, how are you?");
});
Output:
Click Event Example
Click on the button, and you can see a pop-up window with a message.
HTML can have the following events:
- Form events: reset, submit, etc.
- Select events: text field, text area, etc.
- Focus event: focus, blur, etc.
- Mouse events: select, mouseup, mousemove, mousedown, click, dblclick, etc.
Below are the Window event attributes:
| Event Event Name | Handler Name | Occurs when |
|---|---|---|
| onBlur | blur | When the form input loses focus |
| onClick | click | When the user clicks on a form element or a link |
| onSubmit | submit | When the user submits a form to the server. |
| onLoad | load | When the page loads in a browser. |
| onFocus | focus | When the user focuses on an input field. |
| onSelect | select | When the user selects the form input field. |
Note: You will learn more about JavaScript Events in our JavaScript tutorial.
Let's see what JavaScript can do:
1) JavaScript can change HTML Content
Example
<!DOCTYPE html>
<html>
<body>
<p>JavaScript can change the content of an HTML element:</p>
<button type="button" id="myBtn"> Click Me! </button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World!";
}
</script>
</body>
</html>
Output:
2) JavaScript can change HTML style
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<script>
function myFunction() {
document.getElementById("demo").style.fontSize = "25px";
document.getElementById("demo").style.color = "brown";
document.getElementById("demo").style.backgroundColor = "lightgreen";
document.getElementById("myBtn").addEventListener("click", myFunction);
}
</script>
<button type="button" id="myBtn"> Click Me! </button>
</body>
</html>
Output:
3) JavaScript can change HTML Attributes
Example
<!DOCTYPE html>
<html>
<body>
<script>
function light(sw) {
var pic;
if (sw == 0) {
pic = "pic_lightoff.png"
} else {
pic = "pic_lighton.png"
}
document.getElementById('myImage').src = pic;
}
</script>
<img id="myImage" src="https://placehold.co/400x300/3498db/ffffff?text=Sample+Image" width="100" height="180">
<p>
<button type="button" onclick="light(1)">Light On</button>
<button type="button" onclick="light(0)">Light Off</button>
</p>
</body>
</html>
Use External Script
If you find yourself in a situation where multiple HTML files require identical scripts, one approach is to store your JavaScript logic in a distinct file and reference it in the HTML documents. These external JavaScript files are typically saved with a .js file extension.
Note: Do not add a <script> tag in the external file, and provide the complete path where you have put the JS file.
Syntax:
<script type="text/javascript" src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image"></script>
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image"> </script>
</head>
<body>
<h2>External JavaScript Example</h2>
<form onsubmit="fun()">
<label>Enter your name:</label><br>
<input type="text" name="uname" id="frm1"><br>
<label>Enter your Email-address:</label><br>
<input type="email" name="email"><br>
<input type="submit">
</form>
</body>
</html>
JavaScript Code:
function fun() {
var x = document.getElementById("frm1").value;
alert("Hi"+" "+x+ "you have successfully submitted the details");
}
Output:
HTML <script> Tag
The HTML <script> tag is used to specify a client-side script. It may be an internal or external JavaScript that contains scripting statements, hence we can place the <script> tag within the <body> or <head> section.
It is mainly used to manipulate images, form validation , and change content dynamically. JavaScript uses document.getElementById method to select an HTML element .
Example
<!DOCTYPE html>
<html>
<body>
<h2>Use JavaScript to Change Text</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World";
</script>
</body>
</html>
Output:
HTML events with JavaScript
An event is something that a user does, or a browser does, such as a mouse click or page loading, which are examples of events, and JavaScript comes into play if we want something to happen on these events.
HTML provides event handler attributes that work with JavaScript code and can perform an action on an event.
Syntax:
<element event = "JS code">
Example
document.getElementById("myBtn").addEventListener("click", () => {
alert("Hi, how are you?");
});
Output:
Click Event Example
Click on the button, and you can see a pop-up window with a message.
HTML can have the following events:
- Form events: reset, submit, etc.
- Select events: text field, text area, etc.
- Focus event: focus, blur, etc.
- Mouse events: select, mouseup, mousemove, mousedown, click, dblclick, etc.
Following are the list for Window event attributes:
| Event Event Name | Handler Name | Occurs when |
|---|---|---|
| onBlur | blur | When the form input loses focus |
| onClick | click | When the user clicks on a form element or a link |
| onSubmit | submit | When the user submits a form to the server. |
| onLoad | load | When the page loads in a browser. |
| onFocus | focus | When the user focuses on an input field. |
| onSelect | select | When the user selects the form input field. |
Note: You will learn more about JavaScript Events in our JavaScript tutorial.
Let's see what JavaScript can do:
1) JavaScript can change HTML Content
Example
<!DOCTYPE html>
<html>
<body>
<p>JavaScript can change the content of an HTML element:</p>
<button type="button" id="myBtn"> Click Me! </button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World!";
}
</script>
</body>
</html>
Output:
2) JavaScript can change HTML style
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<script>
function myFunction() {
document.getElementById("demo").style.fontSize = "25px";
document.getElementById("demo").style.color = "brown";
document.getElementById("demo").style.backgroundColor = "lightgreen";
document.getElementById("myBtn").addEventListener("click", myFunction);
}
</script>
<button type="button" id="myBtn"> Click Me! </button>
</body>
</html>
Output:
3) JavaScript can change HTML Attributes
Example
<!DOCTYPE html>
<html>
<body>
<script>
function light(sw) {
var pic;
if (sw == 0) {
pic = "pic_lightoff.png"
} else {
pic = "pic_lighton.png"
}
document.getElementById('myImage').src = pic;
}
</script>
<img id="myImage" src="https://placehold.co/400x300/3498db/ffffff?text=Sample+Image" width="100" height="180">
<p>
<button type="button" onclick="light(1)">Light On</button>
<button type="button" onclick="light(0)">Light Off</button>
</p>
</body>
</html>
Use External Script
Suppose you have various HTML files that should have the same script, then we can put our JavaScript code in a separate file and call it in the HTML file. Save JavaScript external files using the .js extension.
Note: Do not add a <script> tag in the external file, and provide the complete path where you have put the JS file.
Syntax:
<script type="text/javascript" src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image"></script>
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image"> </script>
</head>
<body>
<h2>External JavaScript Example</h2>
<form onsubmit="fun()">
<label>Enter your name:</label><br>
<input type="text" name="uname" id="frm1"><br>
<label>Enter your Email-address:</label><br>
<input type="email" name="email"><br>
<input type="submit">
</form>
</body>
</html>
JavaScript Code:
function fun() {
var x = document.getElementById("frm1").value;
alert("Hi"+" "+x+ "you have successfully submitted the details");
}
Output:
HTML <noscript> Tag
The HTML <noscript> tag is used to write disabled script in the browser. The text written within <noscript> </noscript> is displayed only when the browser does not support JS or when JS is disabled. Modern browsers support JS by default, so <noscript> is rarely needed.
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
<noscript>This text is not visible in the browser. </noscript>
</body>
</html>
Best Practices with JavaScript in HTML
In the present day, JavaScript serves a dual purpose of controlling structure and style, in addition to behavior. To enhance readability, it is recommended to extract scripts from HTML and store them in distinct files for reusability, instead of directly embedding code. When declaring variables, the preferred practice among developers has shifted from using var to utilizing let and const, as it contributes to improved code safety and manageability.
Rather than directly incorporating functions through attributes like onclick, JavaScript is usually linked using addEventListener, maintaining the cleanliness of the HTML and focusing on the content. These minor adjustments not only simplify the management of codebases but also enable progressive enhancement, ensuring that users can navigate a website in a fundamental manner even if JavaScript is turned off.
Conclusion
JavaScript empowers developers to engage with HTML web pages by modifying page content, adjusting page styles, and more. Nevertheless, using the <script> tag and event attributes is considered appropriate. It is recommended to enhance code readability by keeping JavaScript and HTML files separate. For instance, incorporating external scripts, utilizing addEventListener, and declaring variables using contemporary syntax. Leveraging HTML, CSS, and JavaScript collectively in a skillful manner allows developers to craft user-friendly, responsive, and dynamic web applications.