Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to write inline JavaScript code in HTML page?
Inline JavaScript refers to JavaScript code written directly within an HTML document using <script> tags, rather than linking to an external JavaScript file. This approach is useful for small scripts or page-specific functionality.
Syntax
To write inline JavaScript, place your code between opening and closing <script> tags:
<script>
// Your JavaScript code here
</script>
Example: Basic Inline JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Inline JavaScript Example</title>
</head>
<body>
<h1 id="heading">Welcome to My Page</h1>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
document.getElementById("heading").innerText = "Text Changed!";
console.log("Button was clicked!");
}
// Code that runs when page loads
console.log("Page loaded successfully");
</script>
</body>
</html>
Script Placement Options
You can place <script> tags in different locations within your HTML:
<!DOCTYPE html>
<html>
<head>
<title>Script Placement</title>
<script>
// Scripts in head run before body elements load
console.log("Script in head executed");
</script>
</head>
<body>
<h1>My Page</h1>
<script>
// Scripts in body run when this point is reached
console.log("Script in body executed");
</script>
<p>Some content here</p>
</body>
</html>
Event Handlers with Inline JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Event Handlers</title>
</head>
<body>
<button onclick="alert('Hello World!')">Simple Alert</button>
<input type="text" onchange="console.log('Input changed:', this.value)">
<div onmouseover="this.style.backgroundColor='yellow'"
onmouseout="this.style.backgroundColor='white'">
Hover over me!
</div>
</body>
</html>
Inline vs External JavaScript
| Aspect | Inline JavaScript | External JavaScript |
|---|---|---|
| Code Organization | Mixed with HTML | Separate files |
| Reusability | Limited to one page | Can be reused across pages |
| Caching | No separate caching | Browser can cache files |
| Best For | Small, page-specific scripts | Large applications |
Best Practices
When using inline JavaScript, place scripts at the end of the <body> tag to ensure DOM elements are loaded before the script runs:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Original text</p>
<!-- Place scripts at the end -->
<script>
// DOM is fully loaded at this point
document.getElementById("demo").innerText = "Text updated by JavaScript";
</script>
</body>
</html>
Conclusion
Inline JavaScript is perfect for small scripts and page-specific functionality. For larger applications, consider using external JavaScript files for better organization and maintainability.
