5 Examples of Applications for Learning JavaScript

9 min read.
Tags: javascript

JavaScript is a programming language used to make a website interactive. For instance, it enables changes when a button is clicked, the creation of animations, development of games, and much more.

On GitHub, JavaScript is the most widely used programming language. Its popularity is driven by numerous prestigious companies creating excellent JavaScript frameworks, such as Facebook with its React and Google with Angular. Additionally, the increasing number of tools that facilitate JavaScript development, like webpack and yarn, along with the continuous evolution of JavaScript itself into a mature programming language (ES6), further bolster its prominence.

Currently, JavaScript is not only used for creating applications that run in browsers but also for developing desktop, mobile, and even IoT applications. The more popular a programming language becomes, the more job opportunities it generates, which is why it’s beneficial to learn JavaScript.

Typically, when starting to learn a programming language, in addition to learning the basics step by step to gradually build up your JavaScript skills, you can also learn from examples. Here are 5 simple application examples for learning JavaScript. These examples are created with pure JavaScript, without libraries like jQuery or others. Each example includes comments on the code lines to explain the purpose of those lines. Hopefully, these JavaScript examples can assist you in your learning journey.

Getting Started

What you need to create and run the JavaScript examples below are:

  • Text editor
  • Web browser

I use Visual Studio Code as the text editor, and Google Chrome as the web browser. You can use other text editors, such as Sublime or Zed. For the web browser, you can use Mozilla or Safari. By the way, Visual Studio Code is made with JavaScript.

Once you have a text editor and web browser, let’s dive straight into the JavaScript examples below.

Hello, World!

It’s almost like a mandatory ritual in tutorials to start with a piece of code that outputs “Hello, world!”. Let’s follow suit with other tutorials. But in this example, there’s not just one “Hello, world!” output, but five. Because there are many ways to display a message in JavaScript.

index.html

<div class="app"></div>

<script src="app.js"></script>

app.js

// Using alert
alert("Hello world!");

// Using console. See the result in the developer console (F12)
console.log("Hello world!");

// Select an existing element and fill it with text
var app = document.querySelector(".app");
app.innerHTML = "Hello world!";

// Directly write text inside the body
document.body.appendChild(document.createTextNode("Hello world!"));

// Create a new element, fill it with text, then add it inside the body
var title = document.createElement("h1");
title.appendChild(document.createTextNode("Hello world!"));
document.body.appendChild(title);

Hello World Demo

The five methods mentioned are as follows: First, we use an alert that appears immediately when the program runs.

Second, using console.log, which displays messages in the developer console (F12 or right-click -> inspect element). Besides displaying messages, console.log can also be used for debugging (finding bugs).

Third, by setting the innerHTML attribute of an existing element in the DOM. We first need to retrieve the element from the DOM using document.querySelector.

Fourth, by directly writing text in the body using appendChild, which serves to insert a Node into an element, and createTextNode, which creates a Text Node.

Lastly, by creating a new element using document.createElement which we then insert into the body element using appendChild.

Timer

The next example is a timer that displays how many seconds the application has been running in the browser. To create this timer, we use setInterval, which will execute a function at specified intervals.

index.html

This website has been running for <b class="timer">0</b> seconds.

<script src="app.js"></script>

app.js

var elapsed = 0;
var start = new Date();
var timer = document.querySelector(".timer");

// Function to calculate the number of seconds that have elapsed
function tick() {
  elapsed = new Date() - start;
  var roundedElapsed = Math.round(elapsed / 100);
  var seconds = (roundedElapsed / 10).toFixed(1);
  timer.innerHTML = seconds + " seconds";
};

// Every 50 milliseconds, run the tick function
setInterval(tick, 50);

Timer Demo

Next is a simple Navigation Menu, where we track which menu item is selected and display it.

index.html

<nav class="nav">
  <a href="#" class="menu is-active" data-value="Home">Home</a>
  <a href="#" class="menu" data-value="Services">Services</a>
  <a href="#" class="menu" data-value="About">About</a>
  <a href="#" class="menu" data-value="Contact Us">Contact Us</a>
</nav>

<div class="info">
  You selected: <span class="selected">Home</span>
</div>

<script src="app.js"></script>

app.js

var selectedMenu = "Home";
var selected = document.querySelector(".selected");
var menus = document.querySelectorAll(".menu");
var activeClass = "is-active";

// https://stackoverflow.com/a/43824723/1240036
function hasClass(el, className) {
  if (el.classList)
    return el.classList.contains(className);
  return !!el.className.match(new RegExp("(\\s|^)" + className + "(\\s|$)"));
}

function addClass(el, className) {
  if (el.classList)
    return el.classList.add(className);
  else if (!hasClass(el, className))
    el.className += " " + className;
}

function removeClass(el, className) {
  if (el.classList)
    el.classList.remove(className);
  else if (hasClass(el, className)) {
    var reg = new RegExp("(\\s|^)" + className + "(\\s|$)");
    el.className = el.className.replace(reg, " ");
  }
}

// Function to set an element as active by adding the class is-active if the element
// has the same data-value, and removing the class is-active if the data-value is not the same
function toggleActive(els, elSelected) {
  els.forEach(function(el) {
    if (el.dataset.value === elSelected.dataset.value) {
      addClass(el, activeClass);
      selected.innerHTML = elSelected.dataset.value;
    } else {
      removeClass(el, activeClass);
    }
  })
}

menus.forEach(function(menu) {
  // Add a listener for the click event, which is toggleActive.
  menu.addEventListener("click", toggleActive.bind(this, menus, menu));
});
You selected: Home

To change the appearance of the currently selected menu, we need to alter the class of the selected navigation menu. That’s why we use three functions that are useful for changing the class of an element.

The first function, hasClass, returns a value of true or false and is used to check whether an element has a specific class or not.

The second function is addClass, which, as the name suggests, is for adding a class to an element. It uses the hasClass function to avoid adding a class if the element already has that class.

The third function, removeClass, is for removing a class from an element. This function also uses the hasClass function, so it only performs the operation of removing the class if the class exists on the element.

Then, there’s the toggleActive function, which we will call when a menu is clicked. To ensure toggleActive is executed upon clicking, we need to register it using addEventListener.

Login Validation

The next example is very simple; we only display a message if the entered email and password do not match and show an alert if they do. In real-world scenarios, validation is performed on the server using ajax.

index.html

<div class="container">
  <form action="" class="form">
    <div class="error" style="display: none"></div>

    <div class="input-field">
      <label for="email">Email</label>
      <input type="text" id="email" />
    </div>

    <div class="input-field">
      <label for="password">Password</label>
      <input type="password" id="password" />
    </div>

    <input type="submit" value="Login">
  </form>
</div>

app.js

var form = document.querySelector(".form");
var error = document.querySelector(".error");
var inputFields = document.querySelectorAll(".input-field");
var email = document.getElementById("email");
var password = document.getElementById("password");

function addError(message) {
  error.innerHTML = message;
  error.style.display = "block";
}

function removeError() {
  error.innerHTML = "";
  error.style.display = "none"; // Change "hidden" to "none" for correct CSS display property
}

function validate(event) {
  // event.preventDefault() stops the form from submitting and sending data to "action".
  event.preventDefault();
  error.style.display = "none";

  if (email.value !== "[email protected]" || password.value !== "password") {
    addError("Email or password is incorrect");
  } else {
    removeError();
    alert("You have successfully logged in!");
  }
}

form.addEventListener("submit", validate);

Login Validation Demo

This example is very straightforward. We simply use error.style.display to make the error element visible or hidden by assigning it the values block and none.

Then, we change the text content of the error element by using innerHTML.

Order Form

Next is an example that’s a bit more complex, involving multiple elements and operations. We’ll create an application to display a list of selectable menu items and then show the total cost that needs to be paid.

index.html

<div class="app"></div>

<script src="helper.js"></script>
<script src="app.js"></script>

helper.js

// https://stackoverflow.com/a/43824723/1240036
function hasClass(el, className) {
  if (el.classList)
    return el.classList.contains(className);
  return !!el.className.match(new RegExp("(\\s|^)" + className + "(\\s|$)"));
}

function addClass(el, className) {
  if (el.classList)
    return el.classList.add(className);
  else if (!hasClass(el, className))
    el.className += " " + className;
}

function removeClass(el, className) {
  if (el.classList)
    el.classList.remove(className);
  else if (hasClass(el, className)) {
    var reg = new RegExp("(\\s|^)" + className + "(\\s|$)");
    el.className = el.className.replace(reg, " ");
  }
}

function currency(amount) {
  return "$" + amount;
}

app.js

var products = [
  {
    id: 1,
    name: "Cappuccino",
    price: 35000,
    active: true,
  },
  {
    id: 2,
    name: "Green Tea Latte",
    price: 40000,
    active: true
  },
  {
    id: 3,
    name: "Fish and Chips",
    price: 50000,
    active: true,
  },
  {
    id: 4,
    name: "Tuna Sandwich",
    price: 45000,
    active: true,
  },
  {
    id: 5,
    name: "Mineral Water",
    price: 8000,
    active: false,
  },
  {
    id: 6,
    name: "French Fries",
    price: 18000,
    active: false,
  },
];

var total = 0;
var app = document.querySelector(".app");

// Render title
function renderTitle(container) {
  var title = document.createElement("h1");
  title.innerHTML = "Order";
  container.appendChild(title);
}

function addTotal(product, total, isAdd) {
  if (isAdd) {
    total += product.price;
  } else {
    total -= product.price;
  }
  return total;
}

// Render list
function renderList(container, products) {
  var orderList = document.createElement("ul");

  products.forEach(function(product) {
    var productItem = document.createElement("li");
    var productPrice = document.createElement("span");

    productPrice.innerHTML = currency(product.price);
    productItem.innerHTML = product.name;
    productItem.appendChild(productPrice);

    orderList.appendChild(productItem);

    productItem.addEventListener("click", function(event) {
      var isAdd = !hasClass(productItem, "is-active");

      if (isAdd) {
        addClass(productItem, "is-active");
      } else {
        removeClass(productItem, "is-active");
      }

      total = addTotal(product, total, isAdd);

      var totalElement = document.querySelector(".total span");
      totalElement.innerHTML = currency(total);
    });
  });

  container.appendChild(orderList);
}

// Render Total
function renderTotalContainer(container, total) {
  var totalContainer = document.createElement("div");
  addClass(totalContainer, "total");

  totalContainer.innerHTML = "Total: ";

  var totalValue = document.createElement("span");
  totalValue.innerHTML = currency(total);
  totalContainer.appendChild(totalValue);

  container.appendChild(totalContainer);
}

renderTitle(app);
renderList(app, products);
renderTotalContainer(app, total);

var productElements = document.querySelectorAll("li");
productElements.forEach(function(productElement, index) {
  if (index < 2) {
    productElement.dispatchEvent(new Event("click"));
  }
});

Order Form Demo

Here we use three functions for class operations similar to the second example: hasClass, addClass, and removeClass. The difference is that here we move them to another file, helpers.js, for better readability. Additionally, in this file, we include the currency function, which simply adds ”$” in front of the amount.

A new function used in this example is dispatchEvent. dispatchEvent is useful for triggering an event listener on an element, which in the above example is “click”, resulting in the top two items being selected.

Conclusion

Learning JavaScript is easy as long as we have the willingness. Generally, operations performed in a JavaScript application include:

  1. Selecting elements in the DOM
  2. Manipulating the DOM (changing element attributes like class)
  3. Creating elements
  4. Adding eventListeners to elements to make them interactive

Of course, there’s much more to learn about JavaScript. Keep up the spirit, and thank you for reading. Don’t forget to share this with your friends too, haha.

Related Posts
Latest Posts