How to Place JavaScript code in HTML

In this article we will discuss about how to insert the JavaScript Code in different ways in HTML file.
  • 1827

There is a facility for JavaScript code that it can be used anywhere in the HTML document but the most commonly preferred ways to embed JavaScript code in our HTML file.

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

JavaScript Code:

<html>

<head>

    <script type="text/javascript">

<!--

        function sayGudmorning() {

            alert("Good Morning")

        }

//-->

    </script>

</head>

<body>

    <input type="button" onclick="sayGudmorning()" value="Say Goodmorning" />

</body>

</html>

Output:

meghamegha1111111111111111.jpg

Example of JavaScript in body and head Section:

<html>

<head>

    <script type="text/javascript">

<!--

        function sayDotnet() {

            alert("Dotnetheaven")

        }

//-->

    </script>

</head>

<body>

    <script type="text/javascript">

<!--

        document.write("Dotnetheaven")

//-->

    </script>

    <input type="button" onclick="sayDotnet()" value="Say Dotnetheaven" />

</body>

</html>

Output:

richa.jpg

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2018 DotNetHeaven. All rights reserved.