Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

JavaScript in Browsers

JavaScript is used a lot in web browsers to enhance the functionality of web applications. JavaScript is mostly used to manipulate HTML elements on a page.

For example, a user can create an element that will show the website's Facebook page then use JavaScript at runtime to dynamically load that page. JavaScript can also be used to enhance functionality by updating only a particular section for the website. Let's say you have a website that shows foreign exchange rates. You can use JavaScript to update the rates table without reloading the whole page.

These are just some of the basic examples of how you can use JavaScript together with HTML content.

Topics to be covered

We will cover the following topics in this lesson

Lesson Prerequisites

For you to successfully complete this lesson, you should have the following requirements

  • NodeJS - we will be executing JavaScript files directly using NodeJS from the command line. Alternatively you can execute the files in the web browser but that takes a a little more time and involves working with multiple programs.
  • Web Browser - a web browser can be used as an alternative to executing JavaScript files that we will be working with.
  • Visual Studio Code - we will be using it as the code editor. It comes with a built-in terminal that will allow us to easily execute JavaScript code from within the text editor. You can also use any code editor that you prefer.
  • JavaScript Basics - this is an added advantage and not mandatory. We will explain every piece of code covered in these lessons.

Lesson Practical Examples Project Setup

This is a practical based lesson. For you to successfully work out the examples given in this lesson, you will need to setup the following directories and files

Create a new directory called javascript-browser

Open the directory javascript-browser in Visual Studio Code or your favorite code editor

Create the following files inside your project folder.

  • index.html - this file will be used to for code dealing with JavaScript within the browser

The following visualizes our project setup

javascript-browser
-index.html

JavaScript Hello World

Let's now create our first JavaScript program. It will be a simple program that displays the message Hello World using an alert box.

Open the the file index.html and add the following code to it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JS Hello World</title>
    <script>
        alert('Hello World')
    </script>
</head>
<body>
</body>
</html>

HERE,

  • <script>...</script> defines the opening and closing tags for the script element. The JavaScript code is written between the opening and closing tags.
  • alert('Hello World') uses the built-in function alert to display a message box in the web browser.

Open the file index.html in the web browser

You should be able to see the following alert message

JavaScript Alert

Let's now look at a more advanced example. We will create an HTML form where the user will enter their name then click on a button that will greet the user by their name.

Replace the contents of index.html with the following code

<!doctype html>
<html lang="en">
    <head>
        <title>JS Hello, world!</title>

        <!-- Bootstrap CSS -->
        <link rel="stylesheet"
            href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
            integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
            crossorigin="anonymous">
    </head>
    <body>
        <div class="container">
            <h2>JavaScript Hello World!</h2>
            <form>
                <div class="form-group">
                  <label for="name">Enter Your Name</label>
                  <input type="text" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Enter name">
                
                </div>
                <button onclick="sayHello()" type="button" class="btn btn-primary">Say Hello</button>
              </form>
              <p id="message">Your message will be displayed here</p>
        </div>
        <script>
            function sayHello(){
                var name = document.getElementById('name').value
                document.getElementById('message').innerHTML = 'Hello ' + name;
            }
        </script>
    </body>
</html>

HERE,

  • <html>...</html> defines a standard HTML document and loads Bootstrap CSS for styling purposes

  • <form>...</form> defines a standard form that contains an input element and a button to click.

    • <input type="text" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Enter name"> defines an input element with the id value of name. We will use this id value to access the value of the input
    • <button onclick="sayHello()" type="button" class="btn btn-primary">Say Hello</button> defines a button element. onclick="sayHello()" defines the JavaScript click event for the button. When the user clicks on the button, JavaScript will call a function called sayHello.
  • <script>...</script> defines the JavaScript function that is executed when the user clicks on Say Hello button. var name = document.getElementById('name').value defines a variable name that is assigned the value of the form input with the id of name. document.getElementById('message').innerHTML = 'Hello ' + name; gets the element with the id of message and replaced its contents with Hello variable_value.

Don't worry if this code looks confusing. We will explain what's going on in more details as the lessons continue. For now the goal is to give you a feel of JavaScript.

Open the file index.html in your web browser.

You should be able to get the following form.

JavaScript Hello World

Enter your first name in the form then click on Say Hello

You should be able to see the following results

JavaScript Hello World

A word about loading JavaScript in browsers

JavaScript should be loaded just before the closing body tag. Loading JavaScript in the head section is considered a bad practice. This is because while the browser is interpreting the code, nothing is displayed in the web browser and this can cause a bad user experience.

Of course you can have special cases where you need to load JavaScript in the head section but this is the exception and not the rule.

The second reason for loading JavaScript at the bottom is that in most cases, you need JavaScript to manipulate the elements on the page. JavaScript code is interpreted line by line from top to bottom. So placing the code at the bottom makes the elements available to JavaScript. If you do it earlier, then the elements to be manipulated may not be available and this can cause an error.

JavaScript Events

Let's now look at events in JavaScript. In fact, we have already looked at an event onclick in the above example. An event is used to define the action that should be taken when the user does something like click a mouse, move the mouse cursor over an element etc.

The following table shows some of the most comment events

EventDescriptionExample
onclickCalled when a user clicks an element<button onclick="eventHandle()">Hit Me</button>
onchangeCalled when the contents of an element change<input onchange="eventHandle" id="name">
onloadExecuted when the browser has loaded the page<body onload="eventHandle">
onkeydownExecuted when a user presses a key on the keyboard`
onmouseoverCalled when a mouse is moved over an element<label onmouseover="eventHandle" for="name">Enter Your Name</label>
onmouseoutExecuted when the mouse pointer moves away from the element<label onmouseout="eventHandle" for="name">Enter Your Name</label>

The above list is not complete. It just shows you some of the most common events that we can work with. We will work with and discover more events as we continue with the lessons.

Summary

Most web browsers come with support for JavaScript out of the box. You can mix HTML with JavaScript to enhance the functionality of web applications. JavaScript code is contained within <script>..</script> tags. JavaScript should be loaded at the bottom of the page to improve the user experience and ensure that the page elements have been loaded and available to JavaScript for manipulation. JavaScript also supports event driven programming.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

JavaScript Setting Up the Development Environment

JavaScript Separation of Concerns

Leave A Reply