Back To The Basics: JavaScript On A Webpage

Javascript on your webpage adds a whole world of interactiveness, flexibility, and potential. As a web developer knowing some javascript will make you a stronger developer and allow you to make single page applications, mac or windows applications, and server applications as well. As they say, “anything that can be written in JavaScript, will eventually be written in JavaScript”. Let’s start from the top and include a javascript script and add in some javascript to a webpage.

First in our index.html, let’s include a reference to a javascript file:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>My Javascript Page</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <h1></h1>
        <script src="scripts/app.js"></script>
    </body>
</html>

We add the reference to our javascript file which is called app.js and is in the directory (folder) called scripts. We put the javascript near the bottom of the body so that the HTML will load first and then the javascript since we want the javascript to interact with the HTML.

Now let’s create a folder called scripts and make a file called app.js. We’ll then make our javascript file, find our empty h1 tag, and insert some content into it:

const heading = document.querySelector('h1');
heading.textContent = 'Hello world!';

If we open our webpage, our h1 will be changed very quickly (basically imperceptibly) from being blank to saying “Hello world”.

Getting started with javascript? Read more about js here

Instagram Post