Normally, there's an ad running in this spot, but you're using an ad blocker. To help support our blog, which provides free tutorials for everybody, we just ask that you whitelist or follow us on facebook, twitter, or subscribe using the form to the leftabove. Thank you!

    Learning JavaScript by Making a Website Interactive

    Now that we've learned the basics of HTML and CSS, we'll be learning the basics of JavaScript to make our websites more dynamic.

    Our pages will no longer be static. We'll be able to change elements in response to user action, and perform calculations in real time. JavaScript makes our website more alive and interactive.

    System requirements

    • A 32-bit or 64-bit computer with at least 8GB of RAM. 16GB or more is recommended.
    • At least 50GB of free disk space.
    • A web browser

    Source Files

    Download the complete working files by clicking here.

    HTML, CSS and JavaScript Files

    After downloading the source files, we should have the following in front of us:

    ▸ my-first-html-website/
    ▸ my-first-html-and-css-website/
    ▾ my-first-html-css-and-js-website/
      ▾ css/
          style.css
      ▾ images/
          codebox_systems_blog_logo.png
      ▾ js/
          main.js
        index.html
    

    Our index.html should now have a <script> tag at the bottom of the page that loads the main.js file.

    By loading the JavaScript file in the body tag and at the end of file, it gets processed after the content is displayed and after all other elements have loaded.

    While you also have the option to load the JavaScript file in the head tag, you'll get errors if you try to target elements that have not yet loaded. The workaround for this is to either do what we've done, or just add code to the JavaScript file that instructs it not to run until the page is ready and elements have fully loaded. We'll be doing both, as a failsafe.

    A Simple Hello World Program

    We'll be writing a few programs throught the course of this tutorial, but will begin with Hello World. This is a simple program that let's the world now your program is alive by announcing "Hello World!". In our previous HTML tutorial, we announced it through the HTML markup. But our JavaScript code will announce it through the browser's console.

    To open up Firefox or Chrome's console, press Ctrl+Shift+J (or Cmd+Shift+J on a Mac).

    You should see "Hello World!" printed to the console.

    JavaScript Basics

    So what exactly is this code? The first concept we need to learn is that JavaScript consists of objects. and console is an object that contains it's own properties and methods/functions. Just like CSS, properties are key-value pairs that define an objects characteristics. So using CSS as an example:

    body {
      color: #000;
    }
    

    In CSS, body would be the object, and color would be the property with color being the key and #000 being the value.

    As we mentioned before, with JavaScript objects, we have methods/functions, as well. A function is invoked/called and it performs some set of actions. With console.log("Hello World!"), we are invoking the log function of the console object and giving it the phrase, "Hello World!" to print out to the browser's console.

    Creating Our First Button

    Now let's check out the next example, which includes a button that will display an alert pop up.

    We now have some extra JavaScript code:

    console.log("Hello World!");
    
    document.getElementById('alert-button').onclick = function() {
      alert("Button was clicked!")
    }
    

    Built-in Functions

    You may have noticed that the alert() function lacks a parent object. alert is one of JavaScript's built-in browser functions. It's available at the root, which is also referred to as the browser's window. So for this browsers tab/window, there exists it's own window object that contains it's properties and methods. So alert can be invoked by calling both alert() or window.alert(). We just don't normally type out window.

    Some other functions at the root or window level include:

    open() Opens a new browser window
    close() Closes the current browser window
    stop() Stops the window from loading
    scrollTo() Scrolls the document to specific coordinates

    Updating Page Content in Real time

    In this updated example, we have a form field and button that allows us to update the h1 title of the page. Notice the id in the h1 tag, which allows us target it through the JavaScript code.

    Now, when you enter text into the form field and click the Submit button, the h1 text will get replaced.

    Understanding the JavaScript

    document.getElementById('main-form').onsubmit = function(evt) {
      evt.preventDefault();
      document.getElementById('main-title').innerHTML = evt.target.title.value;
    }
    

    Event Listeners

    document.getElementById('main-form').onsubmit accepts a function that will fire when the form is submitted by the user clicking the Submit button. onsubmit is called an event handler. It "handles" the submit event. In future tutorials, we'll be learning about dozens of available event listeners that respond to everything from page load to window close.

    Function Steps

    evt.preventDefault() tells the browser not to perform the default form submission behavior. Normally, the form would make a request to a server or API and the browser would then redirect the user to a confirmation page. Because we're preventing this behavior, the form does nothing. We then use the following line to perform our own custom behavior. Basically, we want all of the form functionality that allows us to enter values into the form, but we want to define the rest of the behavior.

    Finally, document.getElementById('main-title').innerHTML = evt.target.title.value; tells the browser to target the inner HTML of the h1 tag we've designated as "main-title" through its id. Currently, the inner HTML is "Hello World! This is my main title.", but we're going to replace it with what the user enters into the form. Let's break down evt.target.title.value below:

    evt The event object that we've named "evt". Whenever an event is handled, the event object is passed into the function, which allows us to access its properties and methods.
    evt.target The "target" of the event handler, which is the form we attached it to
    evt.target.title The input field that we named "title"
    evt.target.title.value The value of the input field we name "title", which is what the user enters.

    So basically, it's just code for selecting the text that the user entered into the field. The event object has hundreds of nested properties and methods that allow us to extract the data we need.

    Conclusion

    That's all for this JavaScript tutorial. Expect many more to come, where we'll expand on the language in detail.

    Did you like this tutorial? Help us pay for server costs by following us on Facebook, Twitter, and subscribing below, where you'll get post notifications, training webinar invites, and free bundles.