JavaScript adds interactivity and visual appeal. Without JS, you wouldn't have interactive elements, animated graphics, and more!
In HTML, JavaScript code is inserted between the
<script> and
</script> tag.
Old JavaScript examples may use a type attribute <script
type="text/javascript">. The type attribute is not
required. JavaScript is the default scripting language in HTML.
function functionName() { ... } A JavaScript function is a block of JavaScript code,
that can be executed when called for by referencing the functionName followed by open and closed parantheses.
An HTML event can be something the browser or a user does. An example of HTML events are an input field was changed or button was clicked. Javascript functions can be used to add event handlers to HTML elements.
<element event='functionName()'> adds an event handler, with JavaScript code, to the HTML element using the event attribute.
In this example, a JavaScript function is placed in the
<head> section of this HTML page. The function is
invoked (called) when a button is clicked. The same function can be added
in the <body> section.
The function name is buttonClick and it is called from an onclick event like onclick="buttonClick()"
The function logic document.getElementById("demo").innerHTML = "Paragraph changed!" changes the HTML content of an element with id="demo".
Example of content in <p> tag changed from a button click event.
In this example, a JavaScript function is placed in the
<body> section of this HTML page. The function is
invoked (called) when an input is changed. The same function can be added
in the <head> section.
The function name is inputChange and it is called from an onchange event like onchange="inputChange()"
The function logic alert("Your favorite color is " + val + "!"); displays an alert box with content and the user provided value.
Example of content captured in <input> tag displayed in an alert notification from an input change event.
Type your favorite color then press enter or click outside the field to fire the onchange event.
I added the buttonClick() Javascript function to the javascript.js file. If I add this code snippet <script src="javascript.js"></script> to the <body> or <head> section, the function will be called from the element the calling function is tied to.