How to Embed JavaScript in HTML

In this tutorial we will show you how to include JavaScript in . At the beginning we will include a brief introduction to JavaScript, while the rest of the guide will focus on various ways to embed JavaScript in HTML.

If you want to display static content, for example a set of images, HTML can do the job for you. However, static pages are slowly becoming a thing of the past. Most content today is interactive and includes eye-catching slideshows, forms, and menus. These enhance the user experience and add dynamism to the website. This is achieved with scripting languages ​​and JavaScript is one of the most famous in this sense, since it allows developers to create websites that interact with the user and vice versa. Although there are many other languages ​​available, none of them are as popular as JavaScript. And to use it to its fullest potential, it is used in conjunction with HTML.

Take advantage of our offers and get your web hosting with a 70% discount. Choose the plan that best suits your needs.

Advantages of JavaScript

JavaScript was first known as LiveScript. But since it was a very popular language, he decided to change the name to JavaScript. Its first appearance dates back to 1995 within Netscape 2.0. Here are some of the main advantages of using JavaScript:

Minimal interaction with the server

It is a well-known fact that if you want to optimize the performance of a website, the best way is to reduce communication with the server. JavaScript helps in this regard by validating the information the user enters on the client side. It only sends requests to the server after running the initial validation checks. As a result, the use of resources and the number of requests to the server is significantly reduced.

See also  How to Create an Affiliate Website? - Explanatory video

More complete and user-friendly interfaces

By using JavaScript, you can create interactive client-side interfaces. For example, adding sliders, slideshows, hover effects, drag and drop, etc.

Immediate feedback for the user

By using JavaScript, you can ensure that users get an immediate response. For example, imagine that a user has filled out a form and left a field empty. Without JavaScript validation, they’ll have to wait for the page to reload only to realize they left an empty field. However, with JavaScript, they will be instantly alerted.

easy debugging

JavaScript is an interpreted language, which means that the written code is deciphered line by line. In case of errors, you will get the exact line number where the problem is.

Embed JavaScript in HTML

There are two ways to include JavaScript in HTML and make them work together. Now that we’ve talked about JavaScript and seen what some of its benefits might be, let’s take a look at some of the ways we can connect JavaScript with HTML.

Add JavaScript directly to an HTML file

The first way to insert JavaScript into HTML is direct. You can do it using the tag which should wrap all the JS code you write. JS code can be added:

  • between the labels
  • between the labels

Depending on where you add the JavaScript code in your HTML file, the load will be different. It is usually recommended to add it in the section so that it remains separate from the content of your HTML file. But place it inside can help improve the loading speed, as the content of the website will load faster, and only after that the JavaScript will be processed. For this example, let’s take a look at the following HTML file which should display the current time:

Time right now is:

At this time, the code above does not contain any JavaScript and therefore cannot display the time. We can add the following code to make sure it displays the correct time:

var time = new Date(); console.log(time.getHours() + “:” + time.getMinutes() + “:” + time.getSeconds());

We will wrap this code with the tags and we will place it in the header (head) of the HTML code to guarantee that every time the page is loaded, an alert is generated that shows the current time to the user. This is what the HTML file will look like after adding the code:

Time right now is:

If you want to display the time within the body of the page, you must include the script within the tags of the HTML page. This is what the code will look like when you do it:

Time right now is:

The content of the myscript.js file will be:

let d = new Date(); document.body.innerHTML = "

Time right now is: " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()

"

Note: Here it is assumed that the file myscript.js is in the same directory than the HTML file.

JavaScript example to validate an email address

JavaScript powers your application by helping you validate user input on the client side. One of the most important user data that often needs validation is email addresses. This JavaScript function can help you validate the entered email address before sending it to the server:

function validateEmailAddress(email) { var re = /^((\\.,;:\s@\"]+(\.\\.,;:\s@\"]+)*)|(\". +\"))@((\{1,3}\.{1,3}\.{1,3}\.{1,3}\])|((+\.)+{2,} ))$/; return re.test(email); } function validate() { $("#result").text(""); var emailaddress = $("#email").val(); if (validateEmailAddress(emailaddress)) { $("#result").text(emailaddress + " is valid :)"); $("#result").css("color", "green"); } else { $("#result").text(emailaddress + " is not correct, please retry:("); $("#result").css("color", "red"); } return false; } $("#validate").bind("click", validate);

To attach this function to a form input, you can use the following code:

Enter an email address:

This is the result you would get after combining all the ingredients in an HTML file:

And if the validation is wrong, the result will be different:

Congratulations! You've learned how to embed JavaScript in HTML with some basic examples.

final words

In this article we talk about the two ways to include JavaScript in HTML code, and when you understand it even better, the possibilities to do great things with both of them are endless. JavaScript can be used in combination with HTML to shape modern web applications that are intuitive, interactive, and easy to use. Using simple client-side validation reduces server traffic and improves the overall efficiency of the website.

Gustavo is passionate about creating websites. He focuses on the application of SEO strategies at for Spain and Latin America, as well as the creation of high-level content. When he is not applying new WordPress tricks you can find him playing the guitar, traveling or taking an online course.

Loading Facebook Comments ...
Loading Disqus Comments ...