PHP Tutorial: Javacript Syntax

Javacript Syntax

JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script> HTML tags in a web page.

You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags.

The <script> tag alerts the browser program to start interpreting all the text between these tags as a script. A simple syntax of your JavaScript will appear as follows.

<script>  
 alert("Hello Javatpoint");  
</script> 

First Javascript Program:

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

Here we have added the javascript code between the body tag of html.

Output: Hello World!

Example 2:

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

Here we have added the javascript code between the head tag, when we click on the click button then it will giv the output: Hello Javascript.

We also can create the external javascript file and embed it on any page. The external file provides the code reusablity because single JavaScript file can be used in several html pages.

An external JavaScript file must be saved by .js extension. It is recommended to embed all JavaScript files into a single file. It increases the speed of the webpage.

Let’s create an external JavaScript file that prints Hello Javatpoint in a alert dialog box.

File Name: Test.js

function msg(){  
 alert("Hello Javatpoint");  
}  

Now we can include this file on any html page, like in below file 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> 

 

Next Topic