advanced
 
 

SocialTwist Tell-a-Friend

Introduction Syntax Placement Variables Operators Popup Boxes If Else Statement Switch Case while Loop for Loop break continue Function Array DOM Events Date String Form Validation

JavaScript : Placement

JavaScript code can be written inline (e.g, within HTML tags called event handlers), in script blocks, and in external JavaScript files.

  • Script in <head>...</head> section.
  • Script in <body>...</body> section.
  • Script in and external file and then include in <head>...</head> section.

    Script in <head>...</head> section
    If you want to have a script run on some event, such as on click of a button, then you will place that script inside the head tag.
    For example,

    <html>
    <head>
    <script type="text/javascript">
    <!--
    function HelloWorld() {
       alert("Hello World")
    }
    //-->
    </script>
    </head>
    <body>
    <input type="button" onclick="HelloWorld()" value="Click Me" />
    </body>
    </html>
    
    

    Script in <body>...</body> section
    If you need a script to run as the page loads so that the script generates content in the page, the script goes in the <body> portion of the document.
    For example,

    <html>
    <head>
    </head>
    <body>
    <script type="text/javascript">
    <!--
    document.write("Hello World")
    //-->
    </script>
    </body>
    </html>
    

    Script in and external file
    The script tag provides a mechanism to allow you to store JavaScript in an external file and then include it into your HTML files.
    For example,

    <html>
    <head>
    <script type="text/javascript" src="filename.js" ></script>
    </head>
    <body>
    <p>Using external JavaScript file.<br/>
    <input type="button" onclick="HelloWorld()" value="Click Me" />
    
    </body>
    </html>
    
    

    you can keep following content in filename.js file and then you can use HelloWorld function in your HTML file after including filename.js file:

    function sayHello() {
       alert("Hello World")
    }
    

  • Previous            Next
    Contact Us
    Your Ad Here