9
The primary role of JavaScript is to modify the default behaviors of a web browser. Browsers come programmed with standard approaches to how a web page is rendered and interacted with. Therefore, if you wanted to add or modify an interaction, you’d need to leverage JavaScript to make this happen. Here are some examples of what can be achieved with JavaScript:
- Show a spinner while the page loads (known as a pre-loader). The browser is made to overlay an image while the page renders. Once rendering is completed, the overlay is hidden and the content beneath is revealed.
- Changing how a form submits data. By overriding a form’s action, the standard HTML submission is handled by JavaScript which will submit the form asynchronously (without reloading the page).
- Tracking a user as they navigate your website. JavaScript is used by analytics companies to allow page requests and interactions to be sent to a third-party website. Here are a few analytics companies that provide analytics: Google Analytics, KissMetrics, and Piwik.
- Having an interaction in one area of your website cause a response. Image sliders and carousels are examples of this. Click on a next or previous button to load a new image.
It’s easy to start coding your first script. All modern web browsers ship with JavaScript, so there are no external assets required to program using Vanilla or pure JavaScript. Most developers prefer to use a JavaScript library because they ship with many functions to simplify code. Other developers feel external libraries add a lot of unnecessary bloat since most websites use a fraction of the code available. In either case, JavaScript on its own is powerful enough to cover most use cases.
Pro-tip: Don’t mix JavaScript up with Java. JavaScript is a web language while Java is mainly used to create applications and control embedded circuits. Until recently, JavaScript was only used for frontend or browser-based scripts. Advances in web technologies now allow it to be used on the backend using a language such as Node.js. This means you only need to know JavaScript to control browser behaviours and load content from a database and pre-process content before transferring it to the user’s computer.
Writing Your First Script
The simplest starting point is making an alert appear in the user’s browser window. In the example below, an in-line onclick attribute is used to run a JavaScript alert.
<html> <body> <h1>Your First Script</h1> <button onclick="alert('Hello World!')">Click Me</button> </body> </html>
Figure 9-1 reveals what you would see when you click on the button:
Capturing and Outputting Content
In this example, we will be taking content from an input field and outputting it in a p (paragraph) tag. For this to work, we will need to use the id attribute so that we can target the elements.
<input id="sometext" value="enter anything"> <button type="button" onclick="outputText()">Click</button> <p id="output"></p> <script> function outputText() { document.getElementById('output').innerHTML = document.getElementById('sometext').value; } </script>
This time, we’d separated the script from our HTML. In the previous example, JavaScript was kept inline using the onclick attribute. By separating the JavaScript and keeping it before the closing body tag (hidden in above example), we make our code more manageable and less polluted. The onclick attribute called the JavaScript function called outputText.
Can you see the relationship between the id attributes and the script? We are setting the HTML within output equal to the value of the tag sometext using their id attributes for identification. The standard is to only use an id only once on each page. An ID such as a driver’s license is made to be unique to its holder. Duplicating the same ID is counterfeiting, so avoid doing it with your code.
How JavaScript Works: the DOM
In order to make changes to the browser and the site’s content, JavaScript needs access to the model used to store the browser and page’s parameters. Each parameter is stored as a node in a tree or database called the Document Object Model. Each branch of the document’s data is known as an object. This allows for traversing which just means that JavaScript is tracking and accessing all tags in your HTML file. In the example of Capturing and Outputting content, our document has several id attributes. JavaScript searches our HTML elements for a tag with the id specified.
Let’s break down this code, document.getElementById(‘output’).innerHTML. Each object is separated by a period (.). The first object is the document and we’re looking within it for an element with an id of output. The function in JavaScript called getElementById is what we use to traverse the document and returns it as an object. The object is composed of several attributes, one of which is the innerHTML. For an input element, we use the value attribute to access the input field’s current value. If the user types something into the input field, JavaScript will capture it.
Another example of an object that we can access is the window. The window contains details on the browser’s window. We can use this to capture the user’s location as x and y coordinates.
Mouse Location Example
In the following example, the onmousemove attribute is applied to the html tag. Using this method allows the function to only run when the mouse is moving anywhere on the page. If applied to the body tag, the result would be only executed on the visible contents of the page. We could have used onclick instead, but you’ll find real-time updates quite satisfying compared to clicking to have the value update.
The event object is passed into the showXY function. The object provides the user’s X and Y mouse position so that we can output it into the element with an id of location. In this case, it’s a span element. The function sets the location span equal to event.clientX + “,” + event.clientY. Note the use of a plus (+) sign to append a comma (,) to the value of event.clientX. A string should be encapsulated with quotes. It does not matter if it’s a double quote or a single quote. However, if you want to use double quotes within your text, you’ll need to encapsulate it with single quotes (and vice versa). For example, x = “There’s a small image” and ‘They said, “upload the image” and clicked.’
<!DOCTYPE html> <html onmousemove="showXY(event)"> <body> <p>XY (<span id="location">0,0</span>) </p> <script> function showXY(event) { var coords = event.clientX + "," + event.clientY; // Setup a variable called coords document.getElementById("location").innerHTML = coords; // Output the value in #location } </script> </body> </html>
It’s always a good habit to provide placeholder content. In the location span, 0,0 is provided. This content is replaced once the current mouse position is captured by the browser and processed using the script. In cases where a user is on a slow connection or waiting for external scripts to load, the placeholder content will greet them and provide some direction.