Where To Insert
- In HTML, JavaScript Function is inserted between <script> and </script> tags.
Example:
<script>
document.getElementById("demo").innerHTML = "Welcome to quipoin";
</script>
</script>
<!DOCTYPE html>
<html>
<body>
<h2>Quipoin</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Welcome to quipoin";
</script>
</body>
</html>
Output:
JavaScript in <body>:
- When a JavaScript function is placed in the <body> section of an HTML page.
- The javascript function is called when a button is clicked:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>Demo JavaScript in Body</h2>
<p id="demo">A sentence</p>
<button type="button" onclick="myFunction()">Enter</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "sentence changed.";
}
</script>
</body>
</html>
Output:
On Clicking enter we get:
JavaScript in <head>:
- JavaScript function is placed in the <head> section of an HTML page.
- The javascript function is called when a button is clicked:
Example:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "sentence changed.";
}
</script>
</head>
<body>
<h2>Demo JavaScript in Head</h2>
<p id="demo">sentence</p>
<button type="button" onclick="myFunction()">Enter</button>
</body>
</html>
Output:
After clicking enter: