HTML and Javascript

Javascript, also known as JS, is a programming language used for the web development. It is used to make HTML pages more interactive, and dynamic. For example,

<html>
    <head>
        <script>
            function speak() {
                alert('Hello')
            }
        </script>
    </head>
    <body>
        <button onclick="speak()">Click Me</button>
    </body>
</html>

Browser output (before click)

Image of an alert shown by using internal JS before click

Browser output (after click)

Image of an alert shown by using internal JS after button click

In the above example, we added functionality to the button by making it trigger an alert dialog when clicked.


How to add Javascript

There are two ways to add javascript to your HTML file.

  • Adding an Internal Script
  • Adding an External Script

Adding an Internal Script

We can add Javascript to the HTML document by writing it inside a <script> tag. For example,

<head>
    <title> </title>
    <script>
        function showHiddenText() {
        document.getElementById("demo").innerHTML = "Hello World";
      }
    </script>
</head>
<body>
    <button onclick="showHiddenText()">Click me</button>
    <p id="demo"></p>

</body>

Browser output(before click)

Image of button

Browser output(after click)

Image of a button and text shown by using internal JS

In the above example, Hello World text is shown after button click.

Note: Generally, the script tag is placed in the <head> of the document but there is no restriction on where to place the tag.


Adding an External Script

We can also use an external javascript file in our HTML document. To add an external script, we provide the location of the JS file to the src attribute of a <script> tag. For example,

<script src="scripts/code.js"></script>

Here, we've used code.js file from the scripts folder in our HTML file.

It is helpful when the JavaScript code is larger as it helps us to keep our HTML file small by preventing cluttering. Moreover, it can also be used by the HTML document. This also helps us keep our HTML file small and semantic by preventing cluttering.


HTML <noscript> tag

The HTML <noscript> tag is used to provide information to users who have Javascript disabled or whose browsers don't support Javascript. For example,

<noscript>Please enable Javascript to view this page!</noscript>

The contents of the <noscript> tag only show if the browser cannot run Javascript.

Browser Output

Text inside noscript tag being displayed because of disabled JS

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges