In a web pages, JavaScript code written in <script> tags executes automatically when the page loads it. For example, a page that has some text, JavaScript alert code and two images (in that order), will load the text, pop up the alert, and will only show the images AFTER the alert has been dismissed. In order to keep the alert from happening until we want it to, we need to put the JavaScript code in a function (also known as a method). A function is defined as a type of procedure or routine. The idea is that we encapsulate several lines of code that may need to be called often into a function so that they can be called with a single line. In JavaScript, a function is written using the following code:
function functionName() {
//lines of code go here
}
Where "functionName" is any valid identifier name. Like with variables, the name should be indicative of what the function does. If the function is designed to calculate a persons pay, we may call it calculatePay. Regardless of the name, it should always be followed by a set of parenthesis () and curly braces {}. All of the code for the method goes in the curly braces.
function alertHello(){
window.alert("Hello");
}
Any JavaScript code can be placed in a function. We can write functions that would draw shapes on a canvas, ask users for information and perform calculations, etc. The main difference at this point, is that the code in a function WILL NOT EXECUTE until we call it, whereas all other JavaScript on the page will execute as it is loaded.
Also remember that we learned to write functions that take parameters. This allows our functions to be more generic and useful. Below are some examples of functions that use paramters:
function midpoint(x, y){
window.alert("The midpoint is "+((x+y)/2));
}
function changeFontColor(textColor, id){
let node=document.getElementById(id);
node.style.color=textColor;
}
Introduction to Events
Events are actions, triggered by a user, that cause code to be executed. It is the ability to create and handle events that allows JavaScript to help make the web dynamic and interactive. Most often, an event is written as an attribute of an HTML tag and calls a JavaScript method. Here is a list of some basic events and the HTML elements that they can be used on.
onclick
executes on a mouse release that follows a mouse click
works on most elements, typically buttons
onload
executes when the element is loaded
works on most elements, typically used on body and images
onmouseover
executes when the mouse moves over the object
works on most elements
onmouseout
executes when the mouse moves off an object
works on most elements
So, to create a button that will execute the code above, we would create the following code
<button onclick="alertHello()" >Welcome</button>
Introduction to the DOM
The Document Object Model (DOM), is how the browser sees the html presented on a page. The html is represented as a tree structure with the html tag as the root of the tree and the head and body tags as its children. The tree structure is based on parents, children and siblings. This allows javascript to enter, access and modify an HTML document on the fly. Look at the following HTML code and the "tree" view that Javascript forms.
n the DOM, each element on the tree is called a node. These nodes take on a family style relationship. A node above an element on the same path of the tree is called a parent. Nodes below an element on the same path are called children. To elements at the same level with the same parent are called siblings.
The parent of all elements is the html tag. Its children are the header and the body. Since they are at the same level, the head and body tags are called siblings. They each have a child: title is the child of head and p is the child of body. And, each of those children have children. By navigating our way through the dom, we can alter text, style properties, and add, delete or modify nodes.
To access an element in the DOM, we use:
let node=document.getElementById('id');
This is the same code that was used previously to access the an input and the canvas. Now, we can use that to access any element in the document that has been given an id. We can access a variety of CSS values, alter the text of an element, or even change the source of an image.
To change the value of a CSS property, use .style after the node variable and then write the style property that you want to change. Be aware, that CSS styles that use a dash (e.g. background-color), are written without the dash by adding capitalization in JavaScript (e.g. backgroundColor). So, to change the background color of an element with id=homeLink, we would write:
let node=document.getElementById('homeLink');
node.style.backgroundColor='#FF0000';
To change the source of an image, use node.src='newfile'. To change the text in an element, use node.innerHTML='New content'. To get the value of a user input, use node.value.
External Scripts
JavaScript is interpreted by the browser. Thus, it is impossible to have a script on one page influence content on another page. This means, that to create user interactions that exist on multiple pages with in a site (such as menu roll overs, etc), we would have to copy and paste the same script onto each of the pages. This is an inefficient method of programming not just in initial time lost, but also if any changes need to be made to the script, they will have to be made on each page.
An alternative is to take your script and save it in a .js file. JavaScript files must contain only JavaScript, they may not contain any HTML. The code in an external JavaScript file is the same code written inside the <script> tags. An external script may look like this:
navEffects.js
function over(){
let node=document.getElementById('homeBtn');
node.style.backgroundColor="white";
node.style.color="green";
}
Any page with an element with id='homeBtn' on which this script is included will allow the script to execute. If the function needs to be changed, it is then only changed in one place and affects the entire site. External scripts are included using the <script> tag. The script tag requires the source attribute, which is a relative path to the external file and should have a type attribute to tell the browser what type of script to expect (text/javascript).
It is recommended to build the JavaScript within the first page on which it is needed for debugging purposes and then move it to an external file. Also, be sure that you stay consistent with id values across pages for the scripts to be effective. Finally, many developers group their code into similar functions. They then create several .js files and include only the code needed on a given page.