javascript code can be embedded in a web page between
<scriptlangugage=”javascript”></script> tags
To embed JavaScript in a web page, you have a few options:
- Inline JavaScript: You can include JavaScript directly within the HTML document using the
<script>
tag. Here’s an example:
html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inline JavaScript Example</title>
</head>
<body>
<h1>Hello, world!</h1>
<script>
// Inline JavaScript code
alert('This is an inline JavaScript alert!');
</script>
</body>
</html>
- Internal JavaScript: You can include JavaScript within the
<script>
tag in the<head>
or<body>
section of the HTML document. This separates the JavaScript code from the HTML content.
html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Internal JavaScript Example</title>
<script>
// Internal JavaScript code
function greet() {
alert('Hello, world!');
}
</script>
</head>
<body>
<h1 onclick="greet()">Click me!</h1>
</body>
</html>
- External JavaScript: You can link to an external JavaScript file using the
<script>
tag’ssrc
attribute. This is useful for separating HTML content from JavaScript code and for reusing JavaScript across multiple pages.
HTML file:
html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External JavaScript Example</title>
<script src="script.js"></script>
</head>
<body>
<h1 id="greeting">Hello, world!</h1>
<button onclick="changeText()">Change Text</button>
</body>
</html>
JavaScript file (script.js
):
javascript
function changeText() {
document.getElementById('greeting').innerText = 'Goodbye, world!';
}
These are the main ways to embed JavaScript in a web page. Each method has its use case depending on the complexity of the JavaScript code and the desired level of separation between HTML and JavaScript.