JavaScript Example
JavaScript is a simple language that is widely used for adding interactivity to web pages. You can write JavaScript code in three different places: within the <body>
tag, within the <head>
tag, or in an external JavaScript file. This flexibility makes JavaScript a powerful tool for dynamic web development.
JavaScript Example 1: Basic Code within the Body Tag
This example shows how to write JavaScript within the <body>
tag and display dynamic content using the document.write()
method.
Example
<script type="text/javascript">
document.write("JavaScript is a simple language for Javatpoint learners");
</script>
Output
JavaScript is a simple language for Javatpoint learners
JavaScript Example 2: Simple Alert between the Body Tag
In this example, we use the alert()
function to display a message in a dialog box when the page is loaded.
Example
<script type="text/javascript">
alert("Hello Shorat");
</script>
Output
An alert box will appear with the message: "Hello Shorat"
JavaScript Example 3: Code between the Head Tag
This example demonstrates placing JavaScript code inside the <head>
tag and creating a function to display an alert on an onclick
event.
Example
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function msg() {
alert("Hello Shorat");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="Click" onclick="msg()"/>
</form>
</body>
</html>
Output
Welcome to JavaScript
3 Places to Put JavaScript Code
- Between the <body> tag: JavaScript can be included directly in the
<body>
section of the HTML. This is useful for running code after the HTML content is loaded. - Between the <head> tag: JavaScript can also be placed in the
<head>
tag. This is ideal for functions and other JavaScript elements that need to load before the body content. - In an External JavaScript File: JavaScript can be written in separate .js files and linked to the HTML file using the
<script>
tag. This approach keeps code organized and reusable across multiple pages.