HTML, CSS, and JavaScript are the three main languages used in front-end development. HTML is a markup language, while CSS is a styling language. 

JavaScript is an object-oriented programming language mostly used in creating the client side of web and mobile applications. This open-source dynamic language has become one of the most-used programming languages due to its flexibility and ease of understanding. 

With HTML5 and CSS3, you can create static websites. However, to add interactivity to such a site, you must use a programming language such as JavaScript that the browsers understand. 

This article will explain why you need to use JavaScript with HTML, the different approaches to adding JavaScript code to HTML, and the best practices for combining the two languages. 

Why it is crucial to use JavaScript in HTML

<img alt="JavaScript-in-HTML-to-Create-Interactive-Webpages" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/JavaScript-in-HTML-to-Create-Interactive-Webpages.png" data- decoding="async" height="493" src="data:image/svg xml,” width=”740″>
  • Add interactivity: Interactivity is responding to user inputs/ actions in real time without reloading the browser. For instance, you can have a counter that increases by one every time it is clicked. Another example can be a response that tells users that their feedback has been sent every time they click the submit button. 
  • Client-side validation: You can use JavaScript to capture the correct data on forms. For instance, you can use this programming language to validate user inputs on a sign-up page by the email format, the password length, and the combination of characters to use. 
  • DOM Manipulation: JavaScript offers the Document Object Model (DOM), which makes it easy to change the contents of a web page dynamically. With this technology in place, the contents of a page are updated automatically based on the user inputs without reloading the web page. 
  • Cross-browser compatibility: JavaScript is compatible with all modern browsers. Web pages created using HTML, CSS, and JavaScript will thus work perfectly on different browsers. 

Prerequisites 

  • Basic understanding of HTML: You understand basic HTML tags, can add buttons and create forms using HTML. 
  • Basic understanding of CSS: You understand CSS concepts such as id, class, and element selectors. 
  • A code editor: You can use a code editor such as VS Code or Atom. You can also use an online JavaScript compiler if you don’t want to install software on your system. 

How to use JavaScript in HTML

You can use three major approaches to add JavaScript code to HTML. We explore each approach and where it suits best.

#1. Embedding code between and tag

This approach lets you have JavaScript and HTML codes in the same file (HTML file). We can start by creating a project folder where we will demonstrate how it works. You can use these commands to get started;

mkdir javascript-html-playground

cd javascript-html-playground

Create two files; index.html and style.css

Add this starter code to the HTML file;





  

    

    

    

  

  

    
                                 
                          
                          
                    
  

Add this starter code to your CSS file;

.form-container {

    display: flex;

    justify-content: center;

    align-items: center;

    height: 100vh; 

  }

  label {

    display: block;

    margin-bottom: 5px;

    font-weight: bold;

  }

  input[type="text"],

  input[type="email"],

  textarea {

    display: block;

    margin-bottom: 10px;

    padding: 5px;

    border: 1px solid #ccc;

    border-radius: 5px;

    font-size: 8px;

  }

  input[type="submit"] {

    background-color: #4CAF50;

    color: white;

    padding: 5px 10px;

    border: none;

    border-radius: 2.5px;

    font-size: 8px;

    cursor: pointer;

  }

  input[type="submit"]:hover {

    background-color: #3e8e41;

  }

When the web page is rendered, you will have something like this;

<img alt="Login" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/Login-1500×788.png" data- decoding="async" height="788" src="data:image/svg xml,” width=”1500″>

We can now add a simple JavaScript code that says “submitted” when you click the submit button. The refactored HTML code with JavaScript will be;





  

    

    

    

  

  

    
                                 
                          
                          
                    
           function submitted() {         alert("submitted");       }        

When you click the submit button, you will get something similar to this;

<img alt="script" data-id="187916" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/script-1500×766.png" data- decoding="async" height="766" src="data:image/svg xml,” width=”1500″>

Pros of embedding JavaScript code between … tags

  • Fast to implement: Working on the same file can save you time as you can reference your JavaScript code from HTML code from the same file. 
  • Easy to read code: The presence of tags separates HTML from JavaScript codes, making it easier to read and debug. 

Cons of embedding JavaScript code between … tags

  • Makes it hard to reuse code: If you have several forms in your app, it means you will create JavaScript code for every form.
  • Slows performance: Big code blocks on the HTML document can slow loading speeds. 

#2. Inline Code by using JavaScript code directly inside HTML

Instead of enclosing the above JavaScript code in …. tags, you can add it directly to the HTML code. We will use the same HTML code and style sheet (style.css). 





  

    

    

    

  

  

    
                                 
                          
                          
                    
  

When you click submit, a small window on your browser with the words “inline submit” will appear. 

Pros of adding JavaScript as Inline Code

  • Quick to implement: You don’t have to shift from one document to another to write HTML and JavaScript code. 
  • Perfect for a small app: If you have a small app that does not demand much interactivity, inline JavaScript is a perfect choice. 

Cons of adding JavaScript as Inline Code

  • The code is not reusable: If your app has several forms, you will create JavaScript code for every form.
  • Slows performance: Big code blocks on the HTML document can slow loading speeds. 
  • Code readability: As the codebase continues to grow, code readability reduces. 

#3. Creating an External JavaScript file

As your application grows, you will note that adding JavaScript code directly to an HTML file is not a good idea. You are also likely to have web pages with low loading speeds when you have a lot of code on your HTML file. 

Create a new file script.js to carry your JavaScript code. 

Import the script.js file on the HTML file;



   

The new updated HTML page will have this code;





  

    

    

    

    

  

  

    
                                 
                          
                          
                    
  

Add this code to the script.js file;

document.addEventListener("DOMContentLoaded", function() {

    const form = document.querySelector("form");

    form.addEventListener("submit", function(event) {

      event.preventDefault();

      alert("external JS sheet submit");

    });

  });

This JavaScript does the following;

  • We have an event listener that waits for the DOMContentLoaded event to fire. 
  • A callback function is executed after the DOMContentLoaded event is fired.
  • The code uses querySelector to pick a form.
  • We use the event.preventDefault() to prevent the DOM from picking the default behavior (refresh the page or navigate to a new page) when the submit event is triggered. 
  • A message “external JS sheet submit” is fired once the submit event is fired. 
<img alt="external" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/external-1500×780.png" data- decoding="async" height="780" src="data:image/svg xml,” width=”1500″>

JavaScript in HTML: Best Practices

  • Minify file sizes: The larger the file size, the more time it takes to load on the browser. Minifying removes all the unwanted characters in the source code without changing its meaning or performance. You can use tools like Yahoo YUI Compressor and HTMLMinifier to create a compact codebase. 
  • Keep your code organized: This will make your easy to read and maintain. You can use extensions such as Prettier to organize your code. 
  • Use external libraries: If a library can perform a certain task for your app, there is no need to write the code from scratch. However, avoid using multiple libraries that achieve the same goals on the same project. 
  • Optimize JavaScript placement: If you intend to add JavaScript code to your HTML file, ensure it comes after the HTML code. Place the JavaScript between tags before closing the tag. This ensures that HTML content such as text, images, and table load first before JavaScript, improving loading speed. 

Wrapping Up 

You can now comfortably use JavaScript with HTML to create interactive web pages. The approach you will use to merge the two technologies will depend on the nature of the web app you are creating. For instance, you can use inline code when creating a small app. On the other hand, a big app needs an external JavaScript file which you will import into your HTML file. 

Check out JavaScript table libraries that you can use today.