Quick Contact

    Introduction to JavaScript

    JavaScript was initially created to make webpages alive.

    The programs in this language are called scripts. They can be written right in the HTML and execute automatically as the page loads. Scripts are provided and executed as a plain text. They don’t need a special preparation or a compilation to run.

    In this aspect, JavaScript is very different from another language called Java.

    At present, JavaScript can execute not only in the browser, but also on the server, or actually on any device where there exists a special program called the JavaScript engine.

    The browser has an embedded engine, sometimes it’s also called a JavaScript virtual machine.

    Different engines have different codenames, for example:

    • V8 – in Chrome and Opera.
    • SpiderMonkey – in Firefox.
    • …There are other codenames like Trident, Chakra for different versions of IE, ChakraCore for Microsoft Edge, Nitro and SquirrelFish for Safari etc.

    The terms above are good to remember, because they are used in developer articles on the internet. We’ll use them too. For instance, if a feature X is supported by V8, then it probably works in Chrome and Opera.

    JavaScript Can Change HTML Content

    One of many JavaScript HTML methods is getElementById().

    This example uses the method to find an HTML element (with id=demo) and changes the element content (innerHTML) to Hello JavaScript:

    document.getElementById("demo").innerHTML = "Hello JavaScript";
    JavaScript Can Change HTML Styles (CSS)

    Changing the style of an HTML element, is a variant of changing an HTML attribute:

    document.getElementById("demo").style.fontSize = "35px";
    or
    document.getElementById('demo').style.fontSize = '35px';
    
    JavaScript Can Hide HTML Elements

    Hiding HTML elements can be done by changing the display style:

    document.getElementById("demo").style.display = "none";
    or
    document.getElementById('demo').style.display = 'none';
    
    JavaScript Can Show HTML Elements

    Showing hidden HTML elements can also be done by changing the display style:

    document.getElementById("demo").style.display = "block";
    or
    document.getElementById('demo').style.display = 'block';
    

    In HTML, JavaScript code must be inserted between <script> and </script> tags.

    <script>
    document.getElementById("demo").innerHTML = "My First JavaScript";
    </script>
    
    JavaScript Functions and Events

    A JavaScript function is a block of JavaScript code, that can be executed when called for.

    For example, a function can be called when an event occurs, like when the user clicks a button.

    JavaScript in <head> or <body>

    You can place any number of scripts in an HTML document.

    Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

    JavaScript in <head>

    In this example, a JavaScript function is placed in the <head> section of an HTML page.

    The function is invoked (called) when a button is clicked:

    <!DOCTYPE html>
    <html>
    <head>
    <script>
    function myFunction() {
        document.getElementById("demo").innerHTML = "Paragraph changed.";
    }
    </script>
    </head>
    <body>
    <h1>A Web Page</h1>
    <p id="demo">A Paragraph</p>
    <button type="button" onclick="myFunction()">Try it</button>
    </body>
    </html>
    
    JavaScript in <body>

    In this example, a JavaScript function is placed in the (body) section of an HTML page.

    The function is invoked (called) when a button is clicked:

    <!DOCTYPE html>
    <html>
    <body>
    
    <h1>A Web Page</h1>
    <p id="demo">A Paragraph</p>
    <button type="button" onclick="myFunction()">Try it</button>
    
    <script>
    function myFunction() {
       document.getElementById("demo").innerHTML = "Paragraph changed.";
    }
    </script>
    
    </body>
    </html>
    
    External JavaScript

    Scripts can also be placed in external files:

    External file: myScript.js
    function myFunction() {
       document.getElementById("demo").innerHTML = "Paragraph changed.";
    }
    

    External scripts are practical when the same code is used in many different web pages.

    JavaScript files have the file extension .js.

    To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:

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

    You can place an external script reference in (head) or (body) as you like.

    The script will behave as if it was located exactly where the (script) tag is located.

    External JavaScript Advantages

    Placing scripts in external files has some advantages:

    • It separates HTML and code
    • It makes HTML and JavaScript easier to read and maintain
    • Cached JavaScript files can speed up page loads

    To add several script files to one page – use several script tags:

    <script src="myScript1.js"></script>
    <script src="myScript2.js"></script>
    
    Variable, Operators, Conditions
    JavaScript Variables

    JavaScript variables are containers for storing data values.

    In this example, x, y, and z, are variables:

    Example

    var x = 5;
    var y = 6;
    var z = x + y;
    

    From the example above, you can expect:

    x stores the value 5

    y stores the value 6

    z stores the value 11

    Much Like Algebra

    In this example, price1, price2, and total, are variables:

    Example

    var price1 = 5;
    var price2 = 6;
    var total = price1 + price2;
    

    In programming, just like in algebra, we use variables (like price1) to hold values.

    In programming, just like in algebra, we use variables in expressions (total = price1 + price2).

    From the example above, you can calculate the total to be 11.

    JavaScript Identifiers

    All JavaScript variables must be identified with unique names.

    These unique names are called identifiers.

    Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

    The general rules for constructing names for variables (unique identifiers) are:

    • Names can contain letters, digits, underscores, and dollar signs.
    • Names must begin with a letter
    • Names can also begin with $ and _ (but we will not use it in this tutorial)
    • Names are case sensitive (y and Y are different variables)
    • Reserved words (like JavaScript keywords) cannot be used as names
    Declaring (Creating) JavaScript Variables

    Creating a variable in JavaScript is called “declaring” a variable.

    You declare a JavaScript variable with the var keyword:

    var carName;

    After the declaration, the variable has no value. (Technically it has the value of undefined)

    To assign a value to the variable, use the equal sign:

    carName = "Volvo";

    You can also assign a value to the variable when you declare it:

    var carName = "Volvo";
    One Statement, Many Variables

    You can declare many variables in one statement.

    Start the statement with var and separate the variables by comma:

    var person = "John Doe", carName = "Volvo", price = 200;
    JavaScript Operators

    The assignment operator (=) assigns a value to a variable.

    var x = 10;

    The addition operator (+) adds numbers:

    var x = 5;
    var y = 2;
    var z = x + y;
    

    The multiplication operator (*) multiplies numbers.

    var x = 5;
    var y = 2;
    var z = x * y;
    
    JavaScript Arithmetic Operators

    Arithmetic operators are used to perform arithmetic on numbers:

    Operator Description
    + Addition
    Subtraction
    * Multiplication
    / Division
    % Modulus (Division Remainder)
    ++ Increment
    Decrement
    JavaScript Assignment Operators

    Assignment operators assign values to JavaScript variables.

    Operator Example Same As
    = x = y x = y
    += x += y x = x + y
    -= x -= y x = x – y
    *= x *= y x = x * y
    /= x /= y x = x / y
    %= x %= y x = x % y
    JavaScript Comparison Operators
    Operator Description
    == equal to
    === equal value and equal type
    != not equal
    !== not equal value or not equal type
    > greater than
    < less than
    >= greater than or equal to
    <= less than or equal to
    ? ternary operator
    JavaScript Bitwise Operators

    Bit operators work on 32 bits numbers.

    Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number.

    Operator Description Example Same as Result Decimal
    & AND 5 & 1 0101 & 0001 0001 1
    | OR 5 | 1 0101 | 0001 0101 5
    ~ NOT ~ 5 ~0101 1010 10
    ^ XOR 5 ^ 1 0101 ^ 0001 0100 4
    << Zero fill left shift 5 << 1 0101 << 1 1010 10
    >> Signed right shift 5 >> 1 0101 >> 1 0010 2
    >>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010 2
    JavaScript Conditions

    Conditional statements are used to perform different actions based on different conditions.

    Very often when you write code, you want to perform different actions for different decisions.

    You can use conditional statements in your code to do this.

    In JavaScript we have the following conditional statements:

    • Use if to specify a block of code to be executed, if a specified condition is true
    • Use else to specify a block of code to be executed, if the same condition is false
    • Use elseif to specify a new condition to test, if the first condition is false
    • Use switch to specify many alternative blocks of code to be executed
    The if Statement

    Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

    Syntax
    if (condition) {
        block of code to be executed if the condition is true
    }
    

    Example

    Make a “Good day” greeting if the hour is less than 18:00:

    <

    if (hour < 18) {
        greeting = "Good day";
    }
    

    The result of greeting will be:

    Good day
    The else Statement

    Use the else statement to specify a block of code to be executed if the condition is false.

    if (condition) {
        block of code to be executed if the condition is true
    } else { 
        block of code to be executed if the condition is false
    }
    

    Example

    If the hour is less than 18, create a “Good day” greeting, otherwise “Good evening”:

    if (hour < 18) {
        greeting = "Good day";
    } else {
        greeting = "Good evening";
    }
    

    The result of greeting will be:

    Good day
    The else if Statement

    Use the else if statement to specify a new condition if the first condition is false.

    Syntax
    if (condition1) {
        block of code to be executed if condition1 is true
    } else if (condition2) {
        block of code to be executed if the condition1 is false and condition2 is true
    } else {
        block of code to be executed if the condition1 is false and condition2 is false
    }
    

    Example

    If time is less than 10:00, create a “Good morning” greeting, if not, but time is less than 20:00, create a “Good day” greeting, otherwise a “Good evening”:

    if (time < 10) {
        greeting = "Good morning";
    } else if (time < 20) {
        greeting = "Good day";
    } else {
        greeting = "Good evening";
    }
    

    The result of greeting will be:

    Good day
    Looping and Array
    JavaScript Loops

    Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true.Very often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.

    In JavaScript there are two different kind of loops:

    • for – loops through a block of code a specified number of times
    • while – loops through a block of code while a specified condition is true
    The For Loop

    The for loop is used when you know in advance how many times the script should run.

    Syntax
    for (var=startvalue;var<=endvalue;var=var+increment) 
    {
    code to be executed
    }
    

    Example

    Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

    Note: The increment parameter could also be negative, and the <= could be any comparing statement.

    <html>
    <body>
    <script type="text/javascript">
    var i=0
    for (i=0;i<=10;i++)
    {
    document.write("The number is " + i)
    document.write("<br />")
    }
    </script>
    </body>
    </html>
    

    Example 2

    How to use the for loop to loop through the different HTML headers.

    <html>
    <body>
    <script type="text/javascript">
    for (i = 1; i <= 6; i++)
    {
      document.write("<h" + i + ">This is header " + i)
      document.write("</h" + i + ">")
    }
    </script>
    </body>
    </html>
    
    The While Loop

    The while loop is used when you want the loop to execute and continue executing while the specified condition is true.

    while (var<=endvalue)
    {
        code to be executed
    }
    

    Note: The <= could be any comparing statement.

    Example

    Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

    <html>
    <body>
    <script type="text/javascript">
    var i=0
    while (i<=10)
    {
    document.write("The number is " + i)
    document.write("<br />")
    i=i+1
    }
    </script>
    </body>
    </html>
    
    Result

    The number is 0

    The number is 1

    The number is 2

    The number is 3

    The number is 4

    The number is 5

    The number is 6

    The number is 7

    The number is 8

    The number is 9

    The number is 10

    The do…while Loop

    The do…while loop is a variant of the while loop. This loop will always execute a block of code ONCE, and then it will repeat the loop as long as the specified condition is true. This loop will always be executed at least once, even if the condition is false, because the code is executed before the condition is tested.

    do
    {
        code to be executed
    }
    while (var<=endvalue)
    Example
    <html>
    <body>
    <script type="text/javascript">
    var i=0
    do 
    {
    document.write("The number is " + i)
    document.write("<br />")
    i=i+1
    }
    while (i<0)
    </script>
    </body>
    </html>
    

    Result

    The number is 0
    Break and Continue

    There are two special statements that can be used inside loops: break and continue.

    Break

    The break command will break the loop and continue executing the code that follows after the loop (if any).

    Example

    <html>
    <body>
    <script type="text/javascript">
    var i=0
    for (i=0;i<=10;i++)
    {
    if (i==3){break}
    document.write("The number is " + i)
    document.write("<br />")
    }
    </script>
    </body>
    </html>
    
    Result
    The number is 0
    The number is 1
    The number is 2
    Continue

    The continue command will break the current loop and continue with the next value.

    Example

    <html>
    <body>
    <script type="text/javascript">
    var i=0
    for (i=0;i<=10;i++)
    {
    if (i==3){continue}
    document.write("The number is " + i)
    document.write("<br />")
    }
    </script>
    </body>
    </html>
    
    Result
    The number is 0
    The number is 1
    The number is 2
    The number is 4
    The number is 5
    The number is 6
    The number is 7
    The number is 8
    The number is 9
    The number is 10
    For … In

    The for…in statement is used to loop (iterate) through the elements of an array or through the properties of an object.

    JavaScript For…In Statement

    The for…in statement is used to loop (iterate) through the elements of an array or through the properties of an object.

    The code in the body of the for … in loop is executed once for each element/property.

    Syntax
    for (variable in object)
    {
        code to be executed
    }
    

    The variable argument can be a named variable, an array element, or a property of an object.

    Example

    Using for…in to loop through an array:

    <html>
    <body>
    <script type="text/javascript">
    var x
    var mycars = new Array()
    mycars[0] = "Saab"
    mycars[1] = "Volvo"
    mycars[2] = "BMW"
    for (x in mycars)
    {
    document.write(mycars[x] + "<br />")
    }
    </script>
    </body>
    </html>
    
    JavaScript Arrays

    An array is a special variable, which can hold more than one value at a time.

    If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

    var car1 = "Saab";
    var car2 = "Volvo";
    var car3 = "BMW";
    

    However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

    The solution is an array!

    An array can hold many values under a single name, and you can access the values by referring to an index number.

    Using an array literal is the easiest way to create a JavaScript Array.

    Syntax:

    var array_name = [item1, item2, ...];       

    Example

    var cars = ["Saab", "Volvo", "BMW"];
    Using the JavaScript Keyword new

    The following example also creates an Array, and assigns values to it:

    Example

    var cars = new Array("Saab", "Volvo", "BMW");
    Access the Elements of an Array

    You refer to an array element by referring to the index number.

    This statement accesses the value of the first element in cars:

    var name = cars[0];

    This statement modifies the first element in cars:

    cars[0] = "Opel";

    Example

    var cars = ["Saab", "Volvo", "BMW"];
    document.getElementById("demo").innerHTML = cars[0];
    
    Arrays are Objects

    Arrays are a special type of objects. The typeof operator in JavaScript returns object for arrays.

    But, JavaScript arrays are best described as arrays. Arrays use numbers to access its elements. In this example, person[0] returns John:

    Array:

    var person = ["John", "Doe", 46];

    Objects use names to access its “members”. In this example, person.firstName returns John:

    Object:

    var person = {firstName:"John", lastName:"Doe", age:46};
    The length Property

    The length property of an array returns the length of an array (the number of array elements).

    Example

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    fruits.length;                       // the length of fruits is 4
    
    Looping Array Elements

    The best way to loop through an array, is using a for loop:

    Example

    var fruits, text, fLen, i;
    fruits = ["Banana", "Orange", "Apple", "Mango"];
    fLen = fruits.length;
    text = "<ul>";
    for (i = 0; i < fLen; i++) {
        text += "<li>" + fruits[i] + "</li>";
    }
    
    Associative Arrays

    Many programming languages support arrays with named indexes.

    Arrays with named indexes are called associative arrays (or hashes).

    JavaScript does not support arrays with named indexes.

    In JavaScript, arrays always use numbered indexes.

    Example

    var person = [];
    person[0] = "John";
    person[1] = "Doe";
    person[2] = 46;
    var x = person.length;         // person.length will return 3
    var y = person[0];             // person[0] will return "John"
    
    JavaScript Array Methods

    The JavaScript method toString() converts an array to a string of (comma separated) array values.

    Example

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo").innerHTML = fruits.toString();
    

    Result

    Banana,Orange,Apple,Mango

    The join() method also joins all array elements into a string.

    It behaves just like toString(), but in addition you can specify the separator:

    Example

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo").innerHTML = fruits.join(" * ");
    

    Result

    Banana * Orange * Apple * Mango
    Popping

    The pop() method removes the last element from an array:

    Example

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    fruits.pop();// Removes the last element ("Mango") from fruits
    
    Pushing

    The push() method adds a new element to an array (at the end):

    Example

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    fruits.push("Kiwi");//  Adds a new element ("Kiwi") to fruits
    
    Deleting Elements

    Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator delete:

    Example

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    delete fruits[0];// Changes the first element in fruits to undefined
    
    Merging (Concatenating) Arrays

    The concat() method creates a new array by merging (concatenating) existing arrays:

    Example (Merging Two Arrays)

    var myGirls = ["Cecilie", "Lone"];
    var myBoys = ["Emil", "Tobias", "Linus"];
    var myChildren = myGirls.concat(myBoys);// Concatenates (joins) myGirls and myBoys
    
    JavaScript Sorting Arrays

    The sort() method sorts an array alphabetically:

    Example

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    fruits.sort();// Sorts the elements of fruits
    
    Reversing an Array

    The reverse() method reverses the elements in an array.

    You can use it to sort an array in descending order:

    Example

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    fruits.sort();// First sort the elements of fruits 
    fruits.reverse();// Then reverse the order of the elements
    
    Introduction to Functions

    A JavaScript function is a block of code designed to perform a particular task.

    A JavaScript function is executed when something invokes it (calls it).

    Example

    function myFunction(p1, p2) {
    return p1 * p2;  // The function returns the product of p1 and p2
    }
    
    JavaScript Function Syntax

    A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

    Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

    The parentheses may include parameter names separated by commas:

    (parameter1, parameter2, ...)

    The code to be executed, by the function, is placed inside curly brackets: {}

    function name(parameter1, parameter2, parameter3) {
        code to be executed
    }
    

    Function parameters are listed inside the parentheses () in the function definition.

    Function arguments are the values received by the function when it is invoked.

    Inside the function, the arguments (the parameters) behave as local variables.

    Function Invocation

    The code inside the function will execute when somethinginvokes (calls) the function:

    • When an event occurs (when a user clicks a button)
    • When it is invoked (called) from JavaScript code
    • Automatically (self invoked)
    Function Return

    When JavaScript reaches a return statement, the function will stop executing.

    If the function was invoked from a statement, JavaScript will return to execute the code after the invoking statement.

    Functions often compute a return value. The return value is returned back to the caller:

    Example

    Calculate the product of two numbers, and return the result:
    var x = myFunction(4, 3);    // Function is called, return value will end up in x
    
    function myFunction(a, b) {
        return a * b;         // Function returns the product of a and b
    }
    

    The result in x will be:

    12
    Why Functions?

    You can reuse code: Define the code once, and use it many times.

    You can use the same code many times with different arguments, to produce different results.

    Example

    Convert Fahrenheit to Celsius:

    function toCelsius(fahrenheit) {
        return (5/9) * (fahrenheit-32);
    }
    document.getElementById("demo").innerHTML = toCelsius(77);
    
    The () Operator Invokes the Function

    Using the example above, toCelsius refers to the function object, and toCelsius() refers to the function result.

    Accessing a function without () will return the function definition instead of the function result:

    Example

    function toCelsius(fahrenheit) {
        return (5/9) * (fahrenheit-32);
    }
    document.getElementById("demo").innerHTML = toCelsius;
    
    Popup Boxes (Alert, Confirm, Prompt)

    JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

    Alert Box

    An alert box is often used if you want to make sure information comes through to the user.

    When an alert box pops up, the user will have to click OK to proceed.

    Syntax

    window.alert("sometext");

    The window.alert() method can be written without the window prefix.

    Example

    alert("I am an alert box!");
    Confirm Box

    A confirm box is often used if you want the user to verify or accept something.

    When a confirm box pops up, the user will have to click either OK or Cancel to proceed.

    If the user clicks OK, the box returns true. If the user clicks Cancel, the box returns false.

    Syntax

    window.confirm("sometext");

    The window.confirm() method can be written without the window prefix.

    Example

    if (confirm("Press a button!")) {
        txt = "You pressed OK!";
    } else {
        txt = "You pressed Cancel!";
    }
    
    Prompt Box

    A prompt box is often used if you want the user to input a value before entering a page.

    When a prompt box pops up, the user will have to click either OKor Cancel to proceed after entering an input value.

    If the user clicks OK the box returns the input value. If the user clicksCancel the box returns null.

    Syntax

    window.prompt("sometext","defaultText");

    The window.prompt() method can be written without the window prefix.

    Example

    var person = prompt("Please enter your name", "Harry Potter");
    if (person == null || person == "") {
        txt = "User cancelled the prompt.";
    } else {
        txt = "Hello " + person + "! How are you today?";
    }
    
    Line Breaks

    To display line breaks inside a popup box, use a back-slash followed by the character n.

    Example

    alert("Hello\nHow are you?");
    Form Handling
    Form Validation

    HTML form validation can be done by JavaScript.

    If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being submitted:

    JavaScript Example

    function validateForm() {
        var x = document.forms["myForm"]["fname"].value;
        if (x == "") {
            alert("Name must be filled out");
            return false;
        }
    }
    

    The function can be called when the form is submitted:

    HTML Form Example

    <form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
    Name: <input type="text" name="fname">
    <input type="submit" value="Submit">
    </form>
    
    Data Validation

    Data validation is the process of ensuring that user input is clean, correct, and useful.

    Typical validation tasks are:

    • has the user filled in all required fields?
    • has the user How to use an important programming construct: arrays
    • has the user entered text in a numeric field?

    Most often, the purpose of data validation is to ensure correct user input.

    Validation can be defined by many different methods, and deployed in many different ways.

    Server side validation is performed by a web server, after input has been sent to the server.

    Client side validation is performed by a web browser, before input is sent to a web server.

    HTML Constraint Validation

    HTML5 introduced a new HTML validation concept called constraint validation.

    HTML constraint validation is based on:

    • Constraint validation HTML Input Attributes
    • Constraint validation CSS Pseudo Selectors
    • Constraint validation DOM Properties and Methods
    DOM Manipulation
    DOM (Document Object Model)

    When a web page is loaded, the browser creates a Document Object Model of the page. The HTML DOM model is constructed as a tree of Objects:

    With the object model, JavaScript gets all the power it needs to create dynamic HTML:

    • JavaScript can change all the HTML elements in the page
    • JavaScript can change all the HTML attributes in the page
    • JavaScript can change all the CSS styles in the page
    • JavaScript can remove existing HTML elements and attributes
    • JavaScript can add new HTML elements and attributes
    • JavaScript can react to all existing HTML events in the page
    • JavaScript can create new HTML events in the page
    The DOM Programming Interface

    The HTML DOM can be accessed with JavaScript (and with other programming languages).

    In the DOM, all HTML elements are defined as objects.

    The programming interface is the properties and methods of each object.

    A property is a value that you can get or set (like changing the content of an HTML element).

    A method is an action you can do (like add or deleting an HTML element).

    Example

    The following example changes the content (the innerHTML) of the <p> element with id=”demo”:

    Example

    <html>
    <body>
    
    <p id="demo"></p>
    
    <script>
    document.getElementById("demo").innerHTML = "Hello World!";
    </script>
    
    </body>
    </html>
    

    In the example above, getElementById is a method, while innerHTML is a property.

    The getElementById Method

    The most common way to access an HTML element is to use the id of the element.

    In the example above the getElementById method used id=demo to find the element.

    The innerHTML Property

    The easiest way to get the content of an element is by using the innerHTML property.

    The innerHTML property is useful for getting or replacing the content of HTML elements.

    The HTML DOM Document Object

    The document object represents your web page.

    If you want to access any element in an HTML page, you always start with accessing the document object.

    Below are some examples of how you can use the document object to access and manipulate HTML.

    Finding HTML Elements

    Method Description
    document.getElementById(id ) Find an element by element id
    document.getElementsByTagName(name) Find elements by tag name
    document.getElementsByClassName(name) Find elements by class name

    Adding and Deleting Elements

    Method Description
    document.createElement(element) Create an HTML element
    document.removeChild(element) Remove an HTML element
    document.appendChild(element) Add an HTML element
    document.replaceChild(element) Replace an HTML element
    document.write(text) Write into the HTML output stream
    Finding HTML Elements

    Often, with JavaScript, you want to manipulate HTML elements.

    To do so, you have to find the elements first. There are a couple of ways to do this:

    • Finding HTML elements by id
    • Finding HTML elements by tag name
    Finding HTML Element by Id

    The easiest way to find an HTML element in the DOM, is by using the element id.

    This example finds the element with id=”intro”:

    Example

    var myElement = document.getElementById("intro");

    If the element is found, the method will return the element as an object (in myElement).

    If the element is not found, myElement will contain null.

    Finding HTML Elements by Tag Name

    This example finds all <p> elements:

    Example

    var x = document.getElementsByTagName("p");

    This example finds the element with id=”main”, and then finds all <p> elements inside “main”:

    Changing the HTML Output Stream

    JavaScript can create dynamic HTML content:

    Date: Thu Jun 21 2018 11:40:49 GMT+0530 (India Standard Time)

    In JavaScript, document.write() can be used to write directly to the HTML output stream:

    Example

    <!DOCTYPE html>
    <html>
    <body>
    
    <script>
    document.write(Date());
    </script>
    
    </body>
    </html>
    
    Changing HTML Content

    The easiest way to modify the content of an HTML element is by using the innerHTML property.

    To change the content of an HTML element, use this syntax:

    document.getElementById(id).innerHTML = new HTML

    This example changes the content of a <p> element:

    Example

    <html>
    <body>
    
    <p id="p1">Hello World!</p>
    
    <script>
    document.getElementById("p1").innerHTML = "New text!";
    </script>
    
    </body>
    </html>
    
    Changing HTML Style

    To change the style of an HTML element, use this syntax:

    document.getElementById(id).style.property = new style

    The following example changes the style of a <p> element:

    Example

    <html>
    <body>
    
    <p id="p2">Hello World!</p>
    
    <script>
    document.getElementById("p2").style.color = "blue";
    </script>
    
    <p>The paragraph above was changed by a script.</p>
    
    </body>
    </html>
    
    JavaScript HTML DOM Animation

    To demonstrate how to create HTML animations with JavaScript, we will use a simple web page:

    Example

    <!DOCTYPE html>
    <html>
    <body>
    
    <h1>My First JavaScript Animation</h1>
    
    <div id="animation">My animation will go here</div>
    
    </body>
    </html>
    
    Create an Animation Container

    All animations should be relative to a container element.

    Example

    <div id ="container">
    <div id ="animate">My animation will go here</div>
    </div>
    
    Style the Elements

    The container element should be created with style = position: relative.

    The animation element should be created with style = position: absolute.

    Example

    #container {
        width: 400px;
        height: 400px;
        position: relative;
        background: yellow;
    }
    #animate {
        width: 50px;
        height: 50px;
        position: absolute;
        background: red;
    }
    
    JavaScript HTML DOM Events

    Reacting to Events

    A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.

    To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:

    onclick=JavaScript

    Examples of HTML events:

    • When a user clicks the mouse
    • When a web page has loaded
    • When an image has been loaded
    • When the mouse moves over an element
    • When an input field is changed
    • When an HTML form is submitted
    • When a user strokes a key

    In this example, the content of the <h1> element is changed when a user clicks on it:

    Example

    <!DOCTYPE html>
    <html>
    <body>
    
    <h1 onclick="this.innerHTML = 'Ooops!'">Click on this text!</h1>
    
    </body>
    </html>
    

    In this example, a function is called from the event handler:

    Example

    <!DOCTYPE html>
    <html>
    <body>
    
    <h1 onclick="changeText(this)">Click on this text!</h1>
    
    <script>
    function changeText(id) { 
        id.innerHTML = "Ooops!";
    }
    </script>
    
    </body>
    </html>
    
    Assign Events Using the HTML DOM

    The HTML DOM allows you to assign events to HTML elements using JavaScript:

    Example

    Assign an onclick event to a button element:

    <script>
    document.getElementById("myBtn").onclick = displayDate;
    </script>
    
    JavaScript HTML DOM EventListener

    The addEventListener() method

    Example

    Add an event listener that fires when a user clicks a button:

    document.getElementById("myBtn").addEventListener("click", displayDate);

    The addEventListener() method attaches an event handler to the specified element.

    The addEventListener() method attaches an event handler to an element without overwriting existing event handlers.

    You can add many event handlers to one element.

    You can add many event handlers of the same type to one element, i.e two click events.

    You can add event listeners to any DOM object not only HTML elements. i.e the window object.

    The addEventListener() method makes it easier to control how the event reacts to bubbling.

    When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.

    You can easily remove an event listener by using the removeEventListener() method.

    Syntax

    element.addEventListener(event, function, useCapture);

    The first parameter is the type of the event (like “click” or “mousedown”).

    The second parameter is the function we want to call when the event occurs.

    The third parameter is a boolean value specifying whether to use event bubbling or event capturing. This parameter is optional.

    Add an Event Handler to an Element

    Example

    Alert “Hello World!” when the user clicks on an element:

    element.addEventListener("click", function(){ alert("Hello World!"); });
    Event Bubbling or Event Capturing?

    There are two ways of event propagation in the HTML DOM, bubbling and capturing.

    Event propagation is a way of defining the element order when an event occurs. If you have a <p> element inside a <div> element, and the user clicks on the <p> element, which element’s click event should be handled first?

    In bubbling the inner most element’s event is handled first and then the outer: the <p> element’s click event is handled first, then the <div> element’s click event.

    In capturing the outer most element’s event is handled first and then the inner: the <div> element’s click event will be handled first, then the <p> element’s click event.

    With the addEventListener() method you can specify the propagation type by using the “useCapture” parameter:

    addEventListener(event, function, useCapture);

    The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses the capturing propagation.

    Example

    document.getElementById("myP").addEventListener("click", myFunction, true);
    document.getElementById("myDiv").addEventListener("click", myFunction, true);
    Pre-defined functions

    The JavaScript global properties and functions can be used with all the built-in JavaScript objects.

    constructor()

    Returns the function that created this object’s instance. By default this is the Number object.

    toExponential()

    Forces a number to display in exponential notation, even if the number is in the range in which JavaScript normally uses standard notation.

    toFixed()

    Formats a number with a specific number of digits to the right of the decimal.

    toSource()

    Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object.

    toString()

    Returns a string of either true or false depending upon the value of the object.

    valueOf()

    Returns the primitive value of the Boolean object.

    charAt()

    Returns the character at the specified index.

    charCodeAt()

    Returns a number indicating the Unicode value of the character at the given index.

    concat()

    Combines the text of two strings and returns a new string.

    indexOf()

    Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.

    anchor()

    Creates an HTML anchor that is used as a hypertext target.

    big()

    Creates a string to be displayed in a big font as if it were in a <big> tag.

    blink()

    Creates a string to blink as if it were in a <blink> tag.

    bold()

    Creates a string to be displayed as bold as if it were in a <b> tag.

    fixed()

    Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag

    concat()

    Returns a new array comprised of this array joined with other array(s) and/or value(s).

    every()

    Returns true if every element in this array satisfies the provided testing function.

    filter()

    Creates a new array with all of the elements of this array for which the provided filtering function returns true.

    forEach()

    Calls a function for each element in the array.

    indexOf()

    Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.

    Client Side Validation (Regular Expression)
    Javascript Regular Expressions: Form Validation

    Everyone must have filled an online form at some stage, a form usually asks for information related to name, phone no, address, credit-card no etc.

    In case you didn’t provide information in the format specified by the form field or leave it empty, the message will appear and form cannot be submitted until you get it right.

    This is done using a Javascript program on the client side, the Javascript program uses a regular expression pattern to test the input of each form field.

    Javascript Form Validation: Checking for Empty fields

    Usually, in a form some fields are optional while some fields are mandatory, hence a javascript program is used to check if the input field is empty or null.

    The demo below , uses a function to check if value in the form field is empty or null.

    <!DOCTYPE html>
    <html>
    <head>
    <title>JavaScript Form Validation: Empty form fields  </title>
    <style>body{font-family:Verdana;}</style>
    </head>
    
    <body>
    <script>
      function check(myform){
     if (myform.myname.value == "" || myform.myname.value == null)
     {
       alert("Name is mandatory");
       return false;
     }
        if(myform.myphone.value == "" || myform.myphone.value == null)
        {
          alert("Phone number is mandatory");
          return false;
        }
        else{
          return true;
        }
      }
    </script>
    <form name="formvalidate" action="formprocess.php" 
            method="get" onSubmit="return check(formvalidate)">
    
    <p> Name : 
    <input type="text" size="50" name="myname" /></p>
    
    <p> Phone No : 
    <input type="text" size="50" name="myphone" /></p>
    
    <p>
    <input type="submit" value="Submit" />
    <input type="reset"  value="Clear" />
    </p>
    </form>
    </body>
    </html>
    
    Javascript Form Validation: Alphabetic Data Input

    There may be some form fields whose values must be strictly alphabetic characters, eg: Name, Country, State.

    In the below demo the regular expression looks for one or more uppercase or lowercase letters within the character class [A-Za-z], followed with an end of a line anchor $

    <!DOCTYPE html>
    <html>
    <head>
    <title>JavaScript Form Validation: Valid Zip Code </title>
    <style>body{font-family:Verdana;}</style>
    </head>
    
    <body>
    <script>
      function check_Alpha(letters){
        var regex = /^[a-zA-Z]+$/;
        if(regex.test(letters.yourname.value) == false){
       alert("Name must be in alphabets only");
       letters.yourname.focus();
       return false;
        }
        if(letters.yourname.value == " "){
          alert("Name Field cannot be left empty");
          letters.yourname.focus();
          return false;
        }
        return true;
      }
    </script>
    <form name="alphavalidate" action="form_process.php"
      method="post" onSubmit="return check_Alpha(this)" >
    
      Name : 
    <input type="text" size="40" name="yourname" />
    
    <input type="submit" value="Submit" />
    <input type="reset" />
    </form>
    </body>
    </html>
    
    JavaScript Form Validation: Removing Spaces and Dashes

    Some undesired spaces and dashes from the user input can be removed by using the string object replace() method.

    The regular expression is used to find the characters and then replace them with empty spaces.

    The regular expression is used to find the characters and then replace them with empty spaces.
    <body>
    <script>
      var demoString = "123-45-5675";
      var regex = /[ -]+/g;
      var replacedString = demoString.replace(regex, " ");
      document.write("The Original String was : " + demoString);
      document.write("<br>The replaced String : " + replacedString);
    </script>
    </body>
    </html>
    
    Summary

    The points summarizes the topic above:

    • At present, JavaScript can execute not only in the browser, but also on the server, or actually on any device where there exists a special program called the JavaScript engine.
    • All JavaScript variables must be identified with unique names.
    • An array can hold many values under a single name, and you can access the values by referring to an index number.
    • A JavaScript function is executed when “something” invokes it (calls it).
    • JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
    • The HTML DOM can be accessed with JavaScript (and with other programming languages).

    Enrolled Yourself In Live Training – PHP Training 

    Copyright 1999- Ducat Creative, All rights reserved.