JavaScript

Types of JavaScript

  • On Page JavaScript
  • External JavaScript

  • On Page JavaScript

    Where to write JavaScript in HTML Page?

  • 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.

  • Note:
  • JavaScript statements are separated by semicolons:
  • 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:

    Example

    <!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>

    Run Example>>



    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:


    Example

    <!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>

    Run Example>>




    Note:
  • Placing scripts at the bottom of the element improves the display speed, because script compilation slows down the display.
  • 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:

    Example

    <!DOCTYPE html>
    <html>
    <body>

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

    </body>
    </html>

    Run Example>>