• Get In Touch
May 29, 2017

A Guide to Understanding and Writing Javascript Code

Need Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on.
View Plans

JavaScript is a scripting language widely used for client-side web development. Scripting language is a lightweight programming language. It is programming code that can be inserted into HTML pages and be executed by all modern web browsers.

You can use JavaScript to validate form, change style, change HTML content, etc.

It is a scripting language widely used for client-side web development. It is a dynamic, weakly typed, prototype-based language with first-class functions. JavaScript was influenced by many languages and was designed to look like Java, but be easier for non-programmers to work with.
All you need to run JavaScript is a Normal Browser.

Objectives

The main objective of this course is to get you up to speed with JavaScript language.

There are a lot of examples demonstrating JavaScript functionality and features.

Basic JavaScript Syntax

Before you can write any JavaScript code you need to know how to include it in your documents. There are two ways to do this, you can either include your script between script tags in your HTML file or you can import an external script file.

Usually script tags should be place in the head section of your document but there may be times when you need to include a script block within the body
The following code shows the two methods of including JavaScript in your document.

        <head>
          <script language="JavaScript">
            function doNothing(param1, param2){
              //this function does not do anything
              return param1;
            }
          </script>
          <script language="JavaScript" src="xxx.js"></script>
        </head>

The first script tag includes JavaScript on the page, the second imports from another file. The actual JavaScript code is the same whichever method you use. It is usually a good idea to keep functions that can be reused on several pages in an external file, whereas code relate specifically to this page could be included in a script block.

Introduction to this Keyword

The this keyword is among the most important and powerful in Javascript. It is very important to understand how this keyword works for one to be able to use it.

The this keyword means owner of the function we are the executing or to the object that the method is a member of.

The best way to understand this keyword is through simple examples.

   function changeColor(){
        this.style.color = 'blue';
    }

If you create the above function on a page, then the owner of the function changeColor is the page or the window object. Hence if you run the about function you will get errors because the window object doesn’t have style object.

  • Copying
    In order to use the this keyword to all its capabilities, it is very important to ensure that the correct HTML element owns the function that is going to use it. Let’s use the onclick property of an element. To do this, we need to copy the changeColor function to the onclick property. This property becomes the method.

element.onclick = changeColor;

Here, on execution of the event handler, the HTML element is referred by the keyword this, and the color changes.

  • Referring
  • When referring, the function is usually not copied. It is just refered to, making this a little bit tricky.

<element onclick = "changeColor()">

The actual function is not contained in the onclick property, but in a function call.

changeColor();

Therefore what happens is that, it goes to the changeColor() and executes it.

Errors are the found (in case there are any) when the this keyword arrives at changeColor().

To see the difference between copying and referring use the alert function:

```
    d.onclick = changeColor;
    alert(d.onclick);
```
```
function changeColor(){
    this.style.color = 'blue';
}
```

Looking at the piece of code above, the onclick method has the this keyword. This means that the HTML element has been referred to by the “`this keyword.

Look at the code below;

<div onclick="changeColor()">   
    <script>
        var d = document.getElementsByTagName('div')[0];
        alert(d.onclick);
    </script>

Refreshing the page, this is what you would see:

    function onclick(event){
        changeColor();
    }

In the piece of code above, you can see that we do not have the this keyword in the onclick function. This means that the HTML element has not been referred to by the keyword.

JavaScript Functions

In JavaScript, Functions are objects themselves. As such, they have properties and can be passed around and interacted with like any other object.
Function are very easy to define:

    //function
    function mySchool(school){  
        alert("My School is " + school);        
    }

You can assign functions to variables:

    var move = function (){
        alert("1st Step");
        alert("2nd Step");
        alert("Moved two steps");
    }

The above function is similar/same as:

    function move(){
        alert("Moved two steps");
    }

You can create functions within functions(methods):

    function walk(){
        this.step = 0;
        //method
        this.move = function(){
            this.step ++;
            alert("Step " +this.step);
        }
    }
    walking = new walk();
    walking.move(); //  1st Step
    walking.move(); //  2nd Step
    walking.move(); //  3rd Step

Introduction to DOM Elements

DOM is an acronym for Document Object Model. To allow JavaScript to interact with your document it is represented by a hierarchical set of objects, this set of objects is called the DOM.
Each object exposes various properties and methods, additionally some objects expose collections of other objects. All objects also expose standard properties to allow access to the parent and child objects.
The root object in the hierarchy is the window; the window’s main child element is the document object, which has various children including collections of forms and anchors.
You can reference any object by name or id, the methods document.getElementById(id) and document.getElementByName(name) are useful to avoid working your way down the object hierarchy and helping your code work properly in different browsers.

Customizing Elements

JavaScript enables you to customize existing elements by override certain properties and methods or adding your own methods and properties to the element.

    d = document.createElement('div');
    d.myName = 'Allen';
    d.hello = function(){
        alert("Hello " + d.myName);
}

You can call the variable: d.myName;
You can call the function: d.hello();

Event Handling

Events are action that can be detected by JavaScript. Every element on a web page has certain element that can trigger a JavaScript function. E.g. onClick event of a button element to indicate that a function will run when a user clicks on the button.
Event handling has a cross browser problem. A standard i.e. addEventListener function is used but it does not work for I.E(Internet Explorer).

Registering Event Handlers:

The function addEventListener is normally used as the standard for registering events, but I.E uses the attachEvent function to register events.
The addEventListener is used by most browser apart for I.E(Internet Explorer) which uses the attachEvent function.
Look at the example:

    //The function below make enable cross browser event Registering
            //elem: The element that will contain the event
            //ev:   Event
            //eh:   Event handling Function
            //cb:   caputure or bubble
            function addEvent(elem, ev, eh, cb
                if(elem.addEventListener)
                    alert('Netscape Browser');
                    elem.addEventListener(ev, eh, cb);
                    return true;
                }else if(elem.attachEvent){
                    alert('Microsoft Browser');
                    elem.attachEvent('on'+ev, eh);      }}

Using addEventListener:

element.addEventListener(event,function,boolean);

Looking at the above definition there are 3 arguments. The first argument is the event e.g. the click function serves as the function for event handling, with the boolean (either true or false) is used to show when the eventHandler is supposed to be executed. It can be executed either in the bubbling or the capturing phase. In a situation where you are not sure on either bubbling or the capturing phase, you can use false which is for bubbling. The this keyword always has reference to the element when using addEventListener.

Using attachEvent:

element.attachEvent(event, function);
Looking at the above function, it has two arguments, the event and function. The drawback with this function is that it always uses bubbling and also the event handling function is always referenced not copied hence the this keyword.

Conclusion

This course has handled all the major parts that are required for one to be competent in javascript. Having understood all the bits of it, it is expected that you are now up to speed with javascript and are able to write any piece of code in javascript comfortably.

Need Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on.
View Plans

Share this Article!

Related Posts

Node.js Authentication – A Complete Guide with Passport and JWT

Node.js Authentication – A Complete Guide with Passport and JWT

Truth be told, it’s difficult for a web application that doesn’t have some kind of identification, even if you don’t see it as a security measure in and of itself. The Internet is a kind of lawless land, and even on free services like Google’s, authentication ensures that abuses will be avoided or at least […]

Node.js and MongoDB: How to Connect MongoDB With Node

Node.js and MongoDB: How to Connect MongoDB With Node

MongoDB is a document-oriented NoSQL database, which was born in 2007 in California as a service to be used within a larger project, but which soon became an independent and open-source product. It stores documents in JSON, a format based on JavaScript and simpler than XML, but still with good expressiveness. It is the dominant […]

Using MySQL with Node.js: A Complete Tutorial

Using MySQL with Node.js: A Complete Tutorial

Although data persistence is almost always a fundamental element of applications, Node.js has no native integration with databases. Everything is delegated to third-party libraries to be included manually, in addition to the standard APIs. Although MongoDB and other non-relational databases are the most common choice with Node because if you need to scale an application, […]

Node.Js Vs Django: Which Is the Best for Your Project

Node.Js Vs Django: Which Is the Best for Your Project

Django and NodeJs are two powerful technologies for web development, both have great functionality, versatile applications, and a great user interface. Both are open source and can be used for free. But which one fits your project best? NodeJs is based on JavaScript, while Django is written in Python. These are two equally popular technologies […]

Nodejs Vs PHP:  Which Works Best?

Nodejs Vs PHP: Which Works Best?

Before getting into the “battle” between Node.js and PHP we need to understand why the issue is still ongoing. It all started with the increased demand for smartphone applications, their success forcing developers to adapt to new back-end technologies that could handle a multitude of simultaneous requests. JavaScript has always been identified as a client-side […]