How To Have Javascript In Html

Are you just starting out with web development and want to learn how to include JavaScript in your HTML files? You’ve come to the right place! In this blog post, we will explore two different ways to include JavaScript in your HTML files: using the <script> tag and using the external JavaScript file. Let’s get started!

Using the <script> Tag

The most straightforward way to include JavaScript in your HTML file is by using the <script> tag. The <script> tag can be placed anywhere within your HTML file, but it is commonly placed either in the <head> or near the bottom of the <body> tag. Here’s an example:

Example 1: Including JavaScript in the <head> tag




    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript in Head</title>
    <script>
        function showMessage() {
            alert('Hello, world!');
        }
    </script>


    <h1>Press the button to see the alert!</h1>
    <button onclick="showMessage()">Click me!</button>


Example 2: Including JavaScript at the bottom of the <body> tag




    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript in Body</title>


    <h1>Press the button to see the alert!</h1>
    <button onclick="showMessage()">Click me!</button>

    <script>
        function showMessage() {
            alert('Hello, world!');
        }
    </script>


Using an External JavaScript File

Another way to include JavaScript in your HTML file is by using an external JavaScript file. This method is useful for keeping your HTML and JavaScript code separate, making your code more organized and easier to maintain. In order to include an external JavaScript file, you need to use the <script> tag with the src attribute. Here’s an example:

Example 3: Including an external JavaScript file

Let’s say you have a JavaScript file named script.js with the following content:

function showMessage() {
    alert('Hello, world!');
}

Now, you can include the script.js file in your HTML file using the <script> tag with the src attribute, like this:




    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript External File</title>
    <script src="script.js"></script>


    <h1>Press the button to see the alert!</h1>
    <button onclick="showMessage()">Click me!</button>


Conclusion

In this blog post, we’ve covered two different ways to include JavaScript in your HTML files: using the <script> tag and using an external JavaScript file. Both methods have their own advantages and use cases, so it’s essential to choose the one that best fits your project’s requirements. Now that you know how to include JavaScript in your HTML files, you can start building dynamic and interactive web pages! Happy coding!