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:
HTML file:
Displayed by browser:
<!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>
My Web Page
A Paragraph
It is a good idea to place scripts at the bottom of the <body> element. This
can improve page load, because HTML display is not blocked by scripts loading.