JavaScript Where To
JavaScript can be placed in the <body> and the <head> sections of an HTML page.
The <script> Tag
In HTML, JavaScript code must be inserted between <script> and </script> tags.
Example
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page.
The function is invoked (called) when a button is clicked:
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head><body><h1>My Web Page</h1><p id="demo">A Paragraph</p><button type="button" onclick="myFunction()">Try it</button></body>
</html>
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.
The function is invoked (called) when a button is clicked:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
No comments:
Post a Comment