Getting Started with JavaScript
when we start write javascript code in any web page. Any web page which contain HTML code.So need to add javascript code in webpage HTML.
There three ways to add JavaScript to a web page.
Here, we will describe each one in detail.
1. Adding the JavaScript code between the <script>
You can add the JavaScript code directly within your web pages by placing it between the <script> and </script> tags. The <script> tag indicates the browser that the contained statements are to be interpreted as executable script and not HTML.
Here's an example:
<!DOCTYPE html>
<html>
<body>
<h2>Including the JavaScript code</h2>
<script>
document.write("Tutorialstrend.com!"); // Prints: Tutorialstrend.com!
</script>
</body>
</html>
Output
2. Calling an External JavaScript File and loading it using the src attribute of the <script> tag
You can also place your JavaScript code into a separate file with a .js extension, and then call that file in your document through the src attribute of the <script> tag.
External scripts are useful in practical when the same code is used in many different web pages. It saves you from repeating the same task over and over again, and makes your website much easier to maintain.You can create a external file named - scriptfile.js have the following code.
function myFunction() {
document.getElementById("demo").innerHTML="tutorialstrend.com.";
}
Placing scripts in external files has some advantages:
To use an external script, put the name of the script file in the src attribute of a <script> tag.
<!DOCTYPE html>
<html>
<body>
<h2>Calling External JavaScript</h2>
<p id="demo"></p>
<button type="button" onclick="myFunction()">call external file function</button>
<script src="scriptfile.js"></script>
</body>
</html>
Output
Now click on the button to call external file function.
3. Placing the JavaScript Code inside the HTML tag
You can also place JavaScript code inline by inserting it directly inside the HTML tag using the special tag attributes such as onclick, onmouseover, onkeypress, onload, etc.
<!DOCTYPE html>
<html>
<body>
<h2>Placing the JavaScript Code inside the HTML tag</h2>
<p id="demo"></p>
<button onclick="alert('tutorialstrend.com!')">Click Here</button>
</body>
</html>
Output
Now click on the button to show the alert message.