JavaScript Example
Javascript example is easy to code. JavaScript provides 3 places to put the JavaScript code: within body tag, within head tag and external JavaScript file.
Let’s create the first JavaScript example.
<script type="text/javascript">
document.write("JavaScript is a simple language for javatpoint learners");
</script>
3 Places to put JavaScript code
- Between the body tag of html
- Between the head tag of html
- In .js file (external javaScript)
1) JavaScript Example : code between the body tag
In the above example, we have displayed the dynamic content using JavaScript. Let’s see the simple example of JavaScript that displays alert dialog box.
<script type="text/javascript">
alert("Hello Javatpoint");
</script>
2) JavaScript Example : code between the head tag
<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 JavaScript file
We can create external JavaScript file and embed it in many html page.
It provides code re usability 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.
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>
Post a Comment