Places to put JavaScript code

admin's picture

JavaScript provides 3 places to put the JavaScript code

  1. Between the body tag of html
  2. Between the head tag of html/li>
  3. In .js file (external javaScript)

1.code between the body tag

   <script type="text/javascript"> 
          alert("Hello Javatpoint");  
   </script>

2.code between the head tag

To call function, you need to work on event. Here we are using onclick event to call msg() function.
    <html>  
    <head>  
    <script type="text/javascript">  
    function msg(){  
     alert("Hello Javatpoint");  
    }  
    </script>  
    </head>  
    <body>  
    <p>Welcome to JavaScript</p>  
    <form>  
    <input type="button" value="click" onclick="msg()"/>  
    </form>  
    </body>  
    </html>

 

3. External file.

Let’s create an external JavaScript file that prints Hello Javatpoint in a alert dialog box.
message.js
    function msg(){  
     alert("Hello Javatpoint");  
    } 
Let’s include the JavaScript file into html page. It calls the JavaScript function on button click.

index.html
    <html>  
    <head>  
    <script type="text/javascript" src="message.js"></script>  
    </head>  
    <body>  
    <p>Welcome to JavaScript</p>  
    <form>  
    <input type="button" value="click" onclick="msg()"/>  
    </form>  
    </body>  
    </html>

Technoloies: 

Add new comment