Learn JavaScript Basics in 5 Minutes

ADMEC Multimedia Institute > Web Design > Learn JavaScript Basics in 5 Minutes

Web Development has been taken away like a storm with arise of JavaScript. Almost all the websites that exist consume the power of this scripting language in some way or the other. JavaScript is everywhere, be it websites or native applications. It is one of the renowned languages in the world. Developers swear by it! If you are beginning using JavaScript and want a hold on its basics then you are in the right spot. This article is all about creating a sample project using fundamental blocks of JavaScript under 5 minutes! assuming that you have basic knowledge of HTML and CSS.

<html>
</html>

To gain complete knowledge of JavaScript in the field of web development please check out some of the best JavaScript classroom and online courses that we have designed here at ADMEC.

NOTE: This article does not contain an exhaustive list of all the concepts in JavaScript, the parts that we need to build our sample project have been described below.

Now let’s dive into the basics!

What is JavaScript?

HTML lays down an outline of what goes where on the page, CSS is used to style the elements that have been added and JavaScript is a scripting language that adds interactivity to the web page.

In a gist:

What good is a website if it does not interact? JavaScript lets you update or change content, create animations, add responsive interactions to forms, change or modify styles, take actions on events and much more.

First Things First!

Let’s look at some basics for setting up an HTML file to make it ready to write JavaScript.

  • How to add JS in an HTML file?

Every HTML file has a “head” section. HTML provides a “<script>” tag that lets you add JS in you HTML page like follows:

<script type="text/javascript">
  ....
    <!—JS code goes here -- >
  ....
</script>
<script type="text/javascript">
  ....
    <!—JS code goes here -- >
  ....
</script>
  • What are external JS Scripts?

When there is loads of JS, adding it inside in your HTML file may not be a best practice. An external script file with extension “.js” is created and linked in the HTML file.

Example:

“helloWorld.js”
  • How to link a JS file in HTML?

Once a “js” script file is created it is linked using the “<script>” tag like follows:

Example:

<script src=" "></script>

“src” is the path to the js script file

  • Hello World JS program
<!DOCTYPE html>
<html>
<body>
<script>
     alert(“Hello World!");
</script>
</body>
</html>

Output :

In the above example, “alert” is used to display a “pop-up” message in the browser.

Building Blocks of JavaScript

  • Variables

Imagine you have a box and you put a 10 Rupee note in it. Now this box stores a value. Similarly in JS we have variables as storage for data. We can store data by creating a variable and we can use the contents of this variable to print, alter, and modify its contents.

Example:

var x=10;

Now let’s alert a value stored in a variable:

JS FILE NAMED “hello.js”:

var x = 'hello’;
alert(x);

HTML FILE:

<!DOCTYPE>
<html>
<body>
     <script type="text/javascript" src="hello.js"> </script>
</body>
</html>

OUTPUT:

  • Data Types

A variable in JS can hold certain types of data. The basic types of data a variable can store are:

  • Number– number with or without decimal.

 Example:

var x = 10;
var y = 5.5;
  • String– A series of one or more characters.

 Example:

var x = 'str';
  • Boolean– true or false

 Example:

var x = TRUE;
var y = FALSE;
  • Array– multiple values of the same type in a single variable

 Example:

var x = [1, 2, 3, 4];
var y = [‘a’, ‘b’, ‘c’, ‘d’];
  • Object– multiple values of multiple types in form of ‘property’ ‘value’ pairs. Objects also store methods.

  Example:

var car =
{
     color: ‘Red’,    
     transmission: ‘automatic’,
     type: ‘suv’
}

Object properties are accessed using the “dot notation”:

ObjectName.property

Example:

alert(car.color);

CONDITIONAL STATEMENTS

Many a times we need to perform a set of actions depending on a condition. To create conditional flow we will be using ‘if’ ‘else’ statements:

Syntax:

if(condition)
{
  //action
}
else
{
  //action
}

Here we test if a ‘condition’ holds true we take a certain set of steps , but if the condition is false the program control is passed to the ‘else’ block, and the code written in the else block is executed.

  • Functions

Functions are lines of code put together to perform a task. They are blocks of code that can be called several times in a program this eliminating the need to write same code again and again.

Syntax:

function function_name()
{
  //lines of code
}

Example:

function alertMessage()
{
     alert(‘hello’);
}

Managing the browser: Document + Events

Browser is the interface where the results of JavaScript are displayed. JS lets us add elements, update content, alter HTML elements, take input from end user, trigger actions on certain events etc.

  • DOM- Document Object Model

DOM treats every html tag as an object. An HTML structure can be represented in the form of a tree structure .Let’s look at an example:

HTML:

<!DOCTYPE html>
<html>
<head>
     <title>My title</title>
</head>
<body>
     <a href="https://www.abc.com">My link</a>
     <h1>My header</h1>
</body>
</html>

DOM:

Most top level object in this hierarchy is the ‘document’ object . Using the ‘document’ object we can access/manipulate/update the child nodes. Since every element is treated as an object, JS uses the ‘dot notation’ to access the nodes, like below:

Some of methods of the ‘document’ object that are used to access and manipulate the DOM are:

  • document.getElementById(id) – this method fetches an element using the ‘id’ attribute.
  • document.getElementByClassName(name) – this method fetches an element using the ‘class name’.
  • document.getElementsByTagName(name) – this method fetches an element using the ‘tag name’.
  • Event Handling- Dom Events

HTML DOM lets JavaScript perform a task when an HTML event occurs. Some of these events are:

  • on click of the mouse
  • on change in input field
  • on submit of  form
  • on key up or down
  • on loading of a page etc.

The names of these methods are:

  • onclick() – Triggered when user clicks an element
  • onmouseover() – Triggered  when user moves the mouse over an element
  • onmouseout() – Triggered  when user  moves the mouse away from an element
  • onkeydown() – Triggered  when user  pushes a key on the keyboard
  • onload() – Triggered  when the browser has finished loading the page

Your First JavaScript Application!

We have seen some of the basic features of what JavaScript has to offer; now we will put these into use and create a small “To-Do” application. First, we will begin with adding HTML and CSS and then we will add JS code to make it functional. Let’s look at a screenshot of the application that we are going to create:

This application contains a folder for CSS, a folder for JS and an HTML file:

ToDO.html:

<!DOCTYPE html>
<html lang="en">
<head>
     <title>Document</title>
     <link rel="stylesheet" type="text/css" href="CSS/ToDoStyles.css">
     <script type="text/javascript" src="JS/ToDo.js"></script>
</head>
<body>
<div class="container">
     <div class="headRow">
     <h1>TO-DO APP</h1>
</div>
<br>
<div>
    <input id="userInput" type="text" placeholder="New item...">
    <button id="addBtn" onclick="addNewItem()">Add Item</button>
</div>
<!-- Empty List -->
<div>
     <div class="listItems">
        <ul id="ulList"></ul>
     </div>
</div>
</div>

</body>
</html>

ToDoStyles.CSS:

body
{
     background-color:lightblue;
     text-align: center;
     font-family: 'Open Sans', sans-serif;
     align-content: center;
}
.container
{
    width: 50%;
}
.headRow
{
     border: 3px solid white;
     background-color: blue;
}
h1
{
     color: #ffffff;
     text-transform: uppercase;
     font-weight: 800;
}
#addBtn
{
     border: none;
     padding: 5px 15px;
     border-radius: 5px;
     color: white;
     background-color: #FFCD5D;
     font-weight: bold;
}
#addBtn:hover
{
     background-color: orange;
     color: white;
}
ul
{
     text-align: left;
     margin-top: 20px;
}
li
{
     list-style: none;
     padding: 10px 20px;
     color: #ffffff;
     text-transform: capitalize;
     font-weight: 600;
     border: 2px solid #025f70;
     border-radius: 5px;
     margin-bottom: 10px;
     background: #4EB9CD;
}
li:hover
{
     background: #76CFE0;
}
li > button
{
     font-weight: normal;
     background: none;
     border: none;
     float: right;
     color: #025f70;
     font-weight: 800;
}
input
{
     border-radius: 5px;
     min-width: 65%;
     padding: 5px;
     border: none;
}
.delete
{
     display: none;
}
.strikeThrough
{
     text-decoration:line-through;
}

ToDo.js:

/**Get context of the Add Button***/
  var addButton = document.getElementById("addBtn");

/**The below function is executed when onclick event of the Add button triggers:**/

function addNewItem()
{
    /**Get input from user**/
     var input = document.getElementById("userInput");
     if(input.value!="")
     {
      /**Get context of the Ul element***/
        var ul = document.getElementById("ulList");

      /**Create a new list item**/
        var li = document.createElement("li");
       // creates an element "li"

       /**create text node with input value**/
        var inputValue=document.createTextNode(input.value);

      /**makes text from input field the li text**/
        li.appendChild(inputValue);

      /**Create a delete button dynamically**/
        var deleteBtn=document.createElement("button");

      /**Assign an 'X' to the name of the button***/
        deleteBtn.appendChild(document.createTextNode("x"));
      
      /**Attach an event listener to the delete button on 'click', when clicked 'deleteListItem' method will be called**/
        deleteBtn.addEventListener('click', deleteListItem, false);

      /**Attach the button to the created li**/
        li.appendChild(deleteBtn);
      /**Append li to ul***/
        ul.appendChild(li);
      //Reset text input field
        input.value = "";
    }
    else
    {
       /***If input is empty or blank alert a message**/
        alert("please enter a value");
    }
}
/**function to delete list item on click of 'X'**/
function deleteListItem(e)
{
  /*Here the ‘e’ is aken as an argument parameter, e stands for event, it is an object of the document and hols context of current event*/

var currentLi=e.target.parentElement;
currentLi.setAttribute("class","delete");
}

Explanation:

In this above example, we first created an HTML structure and styled it using CSS. Then in JavaScript:

  1. Get the context of the “addBtn” using getElementByID
  2. When user “clicks” the “addBtn” , the addNewItem() method gets executed as we have assigned the “onClick” property of the “addBtn” to “addNewItem()” as follows:
<button id="addBtn" onclick="addNewItem()">Add Item</button>
  1. In this addNewItem() function, first we fetch the input typed by the user.
  2. If this input is not blank, we dynamically create an Li element and assign the input value to the Li using DOM manipulation methods like “appendChild”, “CreateTextNode” etc
  3. If the input is blank, we alert a message saying “please enter input”.
  4. When we dynamically create an LI, we also attach a delete button to it.
  5. On clicking this button (X) the item gets deleted.
  6. The “deleteBtn” is binded with and event Listener. Event listener looks out for the bound event to happen and then executes a function. In Our Example we bind the “deleteBtn” to an event listener which looks out for the “Click” event.
  7. Once the “Click” event is encountered, “deleteListItem()” method is called.
  8. In this method we make use of the “event” object, in our example “e” is used as a parameter to “deleteListItem ()” method.
  9. The “e.target” property returns the element that triggered the event.
  10. With the returned element, we set the class of the targeted li to “delete” which is defined in our css.

Summary

JavaScript can be considered as vast as a sea! Well it can get overwhelming to grasp in everything at once, but practice can make one sound in this scripting language. Stronger the basics better will be ones programming experience. From variables to functions to conditional statements, every part contributes when coding in JavaScript.

Related Posts

Leave a Reply

Call Now