JavaScript With HTML

Yogesh Kumar
Last Updated: May 13, 2022

Introduction

HTML and JavaScript are two totally different technologies and along with CSS, they make the front-end of the website. We can say these are the three pillars on which our front-end depends. And the most interesting part is that there is no alternative to the above three technologies and you may also say these three are the undisputed king when it comes to front-end development. So, if you want to become a front-end developer, you will have to learn these. 

Front-end is all the visual stuff we see on a particular website. HTML makes the structure of the website, CSS provides the necessary styling to this structure, making it very pleasing to the eye. And finally, javaScript makes the website interactive i.e, what happens when the button is clicked on a website, what needs to be done when a user fills the form, etc. All the interaction with the website is done through javaScript. We can say it makes the website dynamic.

There is a very good analogy that demonstrates the above three technologies. Consider your body is made with HTML and the way you look i.e, your dressing, hair styling, etc are done by CSS. Finally, javaScript is your brain that instructs you what to do in any situation. 

Among these three, HTML and CSS are compulsory but javaScript is optional. You may opt-out to leave javaScript, if you don’t want it. But one question arises, why javaScript is optional? Well, we’ll get to know the reason when we discuss static and dynamic websites.

Static v/s Dynamic Websites

The static website is the one that has a minimalistic design and user interaction. Almost everything on these websites is hardcoded and that is why it is called static as the content in these websites remains static and does not change. The most common example is the blogging website where you just go and read the blog post and can not do anything more than that.

On the other hand, dynamic websites work the other way around. These websites are highly interactive. Contents on these websites are frequently changing based on the user's activities. These kinds of adaptability based on user’s interaction gives these websites dynamic nature. For example, let’s say there is a food ordering website where users can order food, make payments, wishlist restaurants of their choice, etc. shows the dynamic nature of this website.

So, back to our question, why javaScript is optional? Well, for making static websites, you don’t need JavaScript at all, just HTML and CSS is enough. Whereas, JavaScript is just for building web applications i.e, dynamic websites.

How Is JavaScript Different From HTML?

JavaScript is very different from HTML. JavaScript is a fully-fledged programming language whereas HTML is a markup language. Programming language is basically a set of commands used to write computer programs and then this program is converted to machine-readable code. Whereas markup language provides a set of rules for encoding documents that are both human-readable as well as machine-readable.

You can declare variables, write functions, implement conditionals, loop-based on conditions, etc. All the programming concepts are present inside javaScript.

JavaScript on its own is a very vast topic and needs a good amount of time to learn. In this article, we will see how we can provide interactivity to websites using javaScript in conjunction with HTML. 

Integrating JavaScript Inside HTML

We can integrate javaScript inside HTML using <script> tag. We have two options, one is to write the javaScript code between the <script> tag inside an HTML file. And the second option is to write JavaScript code in a separate file and then link that file inside HTML using the src attribute of the <script> tag.

Writing JavaScript code inside HTML file within <script> tag:

 <script>
        // Your code goes here!
  </script>

Writing JavaScript in a separate file ‘index.js’ and linking that file inside HTML. You have to specify the pathname of the file to the src attribute.

   <script src="index.js"></script>

Make sure to not add this <script> tag inside <head> of the HTML as it may slow down your website. When the website loads we always want the visible content of the website to load first and then javaScript to load. For this reason, always specify this <script> tag after <body> tag. Like this,

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>HTML JavaScript</title>
  </head>
  <body>
      <h1>Hey there!</h1>
  </body>
  <script src="index.js"></script>
</html>


If you don’t want to specify the <script> tag after <body> of the HTML and want to specify in the <head> section then you can use defer attribute of the <script> tag which enables the browser to download the script in parallel to parsing the page and execute the downloaded javaScript code only after the page has finished parsing. Like this,
<script src="index.js" defer></script>


Specifying above <script> inside the <head> of the HTML:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="index.js" defer></script>
    <title>HTML JavaScript</title>
  </head>
  <body>
    <h1>Hey there!</h1>
  </body>
</html>

How does JavaScript add Interactivity To a Website?

Common uses for JavaScript are image manipulation, form validation, fetching data from a remote server, dynamic changes of content, etc.

Well, just linking the file and adding the <script> tag won’t do anything, you have to write JavaScript code to perform actions.

Let’s see how JavaScript adds interactivity to the website. For adding interactivity, javaScript needs access to HTML’s in-built DOM API. 

DOM API

DOM is an acronym of Document Object Model which basically has the collection of all the HTML elements like <body>, <p>, <a>, <h1>, etc. 

Apart from these, DOM also has the methods for all HTML elements, and more importantly, it also has the events associated with each HTML element.

Event is basically a kind of situation when something happens like a user clicks an HTML element or the user moves the mouse cursor over an HTML element, etc. Then, JavaScript performs certain actions based on these events.

All these HTML elements are present inside DOM in a hierarchical order. See the figure below which represents the hierarchy among the elements. The <html> elements are the parent of all the elements inside the DOM then <body> and <head> are its direct children and both of them are siblings. Accordingly, the rest of the elements also have some relation among them.

 

Using this DOM API, JavaScript gets access to each and every element of the HTML.  

By making use of this DOM API JavaScript does the following amazing things:

  • JavaScript can add/change/remove HTML elements
  • JavaScript can add/change/remove HTML attributes
  • JavaScript can add/change/remove CSS styles
  • JavaScript can react to all existing HTML events
  • JavaScript can add/change/remove HTML events

Adding and removing elements using JavaScript with HTML:

Firstly, we need to grab an HTML element in JavaScript using DOM API. We can do this in many ways:

Grabbing elements by their class name:

Specify the class name of an element inside the quote.

document.getElementsByClassName(“”);

Here, we grabbed the element <p> having ‘para’ class name and stored it inside the javaScript variable paragraph for further usage of this grabbed element.

<html> 
  <body>
   <h1>Hey there!</h1>
    <p class="para">Hello</p>
  </body>
  <script>
    let paragraph = document.getElementsByClassName("para");
console.log(paragraph);
  </script>
</html>

Here you can see when we are going to print the value of the paragraph variable then we’re going to get the value that is stored in it on the console window and the same thing will remain for the points described below.

Grabbing element by its tag name:

Specify the tag name of an element inside the quote.

document.getElementsByTagName(“”);

Here, we grabbed the element <p> having ‘p’ as its tag name and stored it inside the javaScript variable paragraph for further usage of this grabbed element.

<html> 
  <body>
   <h1>Hey there!</h1>
    <p class="para">Hello</p>
  </body>
  <script>
    let paragraph = document.getElementsByTagName("p");
console.log(paragraph);
  </script>
</html>

Grabbing element by its Id name:

Specify the id of an element inside the quote.

document.getElementById(“”);

Here, we grabbed the element <p> having ‘el’ as its id and stored it inside the javaScript variable paragraph for further usage of this grabbed element.

<html> 
  <body>
   <h1>Hey there!</h1>
    <p class="para" id="el">Hello</p>

  </body>
  <script>
    let paragraph = document.getElementById("el");
console.log(paragraph);
  </script>
</html>

 

Grabbing elements by using CSS selector:

Specify the CSS selector associated with the particular element inside the quote.

document.querySelector(“”);
document.querySelector("p.para");
document.querySelector("p#el");

Here, we grabbed the element <p> having ‘para’ as its CSS selector and we can also use its id as a CSS selector and stored it inside the javaScript variable paragraph for further usage of this grabbed element.

<html> 
  <body>
   <h1>Hey there!</h1>
    <p class="para" id="el">Hello</p>
  </body>
  <script>
    let paragraph = document.querySelector("p.para");
console.log(paragraph);
  </script>
</html>

Now, these are the ways by which we can grab an HTML element in JavaScript. 

After grabbing an element we can now add, change and remove elements in HTML based on this grabbed element.

Adding element using JavaScript with HTML:

For adding an element, we first need to create an element using the createElement() method. Pass the name of the element inside this function to create that element.

const newEl = document.createElement("p");

Then we simply add this created element inside our grabbed element as its child using the appendChild() method. This method takes the created element as its argument.

Let’s  see the complete code for adding elements:

<!DOCTYPE html>
 <html>
  <head>
    <script src="index.js" defer></script>
    <title>Document</title>
  </head>
  <body>
    <h1>Hey there!</h1>
    <div class="container">Container</div>
  </body>
  <script>
    const divEl = document.getElementsByClassName("container");
    const newEl = document.createElement("p");
    divEl.appendChild(newEl);
  </script>
</html>

The newly created paragraph element ‘newEl’ is added as a child of the ‘divEl’ element.

Removing elements using JavaScript with HTML:

We can easily remove the element from HTML using the removeChild() method. Let’s say we want to remove the above-added paragraph element from the <div> tag.

divEl.removeChild(newEl);

Listening To An Event

Remember we discussed an event which is a situation when the user clicks the HTML element, fills the form, etc.  JavaScript specifies what to do if such an event occurs by adding event listeners or event handlers to the HTML element which listens or handles these events by invoking some kind of function. The function is the action that is taken when a certain event is fired.

Some of the important events and event handlers are specified below:

EventsWhen it occursEvent Handlers
clickWhen a user clicks the HTML element.onClick
submitWhen a user submits the form.onSubmit
changeWhen the data in an element is changed by the user.onChange
loadWhen the whole page finished loading.onLoad
focusWhen the object in question gains focus.onFocus

 

We can listen to or handle the above events by specifying an event handler as an attribute to an HTML element on which that event is happening. Like this,

<button onclick=""></button>

Specify the name of the function as a value to this onclick attribute.

 

Understanding By Example

Here, we will be implementing the above concepts in a simple demo example in which the user is greeted by a message when he/she clicks the button.

When you click the button, a click event is fired and you will be greeted. Like this,

Let’s take a look at code for this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Greet Me</title>
    <style>
      body {
        background-color: antiquewhite;
      }

      h1 {
        color: orangered;
        text-align: center;
        font-size: 50px;
      }

      .container {
        display: flex;
        justify-content: center;
      }
      .content {
        display: flex;
        justify-content: center;
        align-items: flex-start;
        width: 40%;
        height: 300px;
        background-color: rgb(188, 145, 231);
        border-radius: 15px;
      }

      button {
        height: 25%;
        width: 25%;
        margin-top: 10px;
        background-color: brown;
        color: bisque;
        font-weight: bold;
        font-size: 20px;
        border-radius: 15px;
      }

      button:hover {
        background-color: bisque;
        color: brown;
      }

      #message {
        position: absolute;
        top: 35%;
        font-weight: 500;
        font-family: sans-serif;
        font-size: 30px;
        color: aliceblue;
      }
    </style>
  </head>
  <body>
    <h1>Click me for a surprise!</h1>
    <div class="container">
      <div class="content">
        <button onclick="displayMessage()">Click here</button>
        <p id="message"></p>
      </div>
    </div>
  </body>
  <script>
    function displayMessage() {
      document.getElementById("message").innerHTML =
        "Good morning! Wish you a very happy day.";
    }
  </script>
</html>

Let’s review the above code:

We simply have an empty <p> element having id ‘message’ to display the greeting message when the user clicks the button.

 <p id="message"></p>

Then we have a button element that fires a click event when it is clicked. We have specified an onclick event handler as an attribute to this which triggers a function displayMessage() when the user clicks the button.

<button onclick="displayMessage()">Click here</button>

Finally, we implemented the displayMessage() function inside our JavaScript which simply grabs the <p> element and injects the message string using innerHTML property. This function is only invoked when the user clicks the button.

<script>
    function displayMessage() {
      document.getElementById("message").innerHTML =
        "Good morning! Wish you a very happy day.";
    }
  </script>

So, that’s it. We have completed this demo using basic JavaScript concepts discussed earlier.

Frequently asked questions

Why is there a need to use JavaScript?

Well, for making our website dynamic and interactive we need JavaScript. Simple static websites don’t require JavaScript at all. Dynamic websites have different logics for each and every event and for implementing these logics we need JavaScript.

 

How can we listen to the event fired by the user?

We can easily listen or handle the event by specifying the event handler attribute inside the HTML element which fires the event. We provide the handling function as a value to this attribute which is invoked when that particular event is fired.

 

How does the appendChild() method work?

This method simply adds the new element as a child to the element we just grabbed. It takes the newly created element as an argument and it calls on the grabbed element. Like this:

 divEl.appendChild(newEl);

Key takeaways

Finally, we are done with this article. We have covered all the basic terminologies and implementation of JavaScript with HTML, we have discovered why there is a need of having JavaScript in every front-end developer’s toolkit. We’ve explored DOM API and its important methods. Got the taste of handling events by using a simple demo example. But still, we barely scratched the surface of JavaScript and of course, this article is just to introduce you to various topics so that you can explore and learn each topic individually in isolation. 

So, this is not the end of the road for you, just mark down these topics and start learning each of them in great detail. We have various articles on these topics which might be helpful to you. So do check out those articles and also keep an eye on our future posts.

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think