Use JavaScript within a webpage
Take your webpages to the next level by harnessing JavaScript. Learn in this article how to trigger JavaScript right from your HTML documents.
| Prerequisites: | You need to be familiar with how to create a basic HTML document. |
|---|---|
| Objective: | Learn how to trigger JavaScript in your HTML file, and learn the most important best practices for keeping JavaScript accessible. |
About JavaScript
JavaScript is a programming language mostly used client-side to make webpages interactive. You can create amazing webpages without JavaScript, but JavaScript opens up a whole new level of possibilities.
Note: In this article we’re going over the HTML code you need to make JavaScript take effect. If you want to learn JavaScript itself, you can start with our JavaScript basics article. If you already know something about JavaScript or if you have a background with other programming languages, we suggest you jump directly into our JavaScript Guide.
How to trigger JavaScript from HTML
Within a browser, JavaScript doesn’t do anything by itself. You run JavaScript from inside your HTML webpages. To call JavaScript code from within HTML, you need the <script> element. There are two ways to use script , depending on whether you’re linking to an external script or embedding a script right in your webpage.
Linking an external script
Usually, you’ll be writing scripts in their own .js files. If you want to execute a .js script from your webpage, just use <script> with an src attribute pointing to the script file, using its URL:
Writing JavaScript within HTML
You may also add JavaScript code between <script> tags rather than providing an src attribute.
That’s convenient when you just need a small bit of JavaScript, but if you keep JavaScript in separate files you’ll find it easier to
- focus on your work
- write self-sufficient HTML
- write structured JavaScript applications
Use scripting accessibly
Accessibility is a major issue in any software development. JavaScript can make your website more accessible if you use it wisely, or it can become a disaster if you use scripting without care. To make JavaScript work in your favor, it’s worth knowing about certain best practices for adding JavaScript:
How to Add JavaScript to HTML

In this tutorial, we’ll show you how to add JavaScript to HTML. The beginning will include a short introduction to JavaScript, while the rest of the guide will focus on various ways of adding JavaScript to HTML.
If you want to display static content, for example, a set of images, then HTML can do the job for you. However, static pages are slowly becoming a thing of the past. Most of the content today is interactive and includes flashy slideshows, forms, and menus. They enhance user experience and add dynamicity to the website.
This is achieved by scripting languages and JavaScript is one of the most famous in this regard. It lets developers make websites that interact with the user and vice versa. Even though there are many other languages available, none of them is as popular as JavaScript. In order to utilize it to the greatest potential, it’s used in tandem with HTML.
How to Add JavaScript to HTML
There are two ways to add JavaScript to HTML and make them work together. Now that we have talked about JavaScript and have seen what some of its advantages can be, let’s take a look at some of the ways we can link JavaScript to HTML.
How to Add JavaScript Directly to a HTML File
The first way to add JavaScript to HTML is a direct one. You can do so by using the <script></script> tag that should encompass all the JS code you write. JS code can be added:
- between the <head> tags
- between the <body> tags
Depending on where you add the code the JavaScript in your HTML file, the loading will differ. The recommended practice is to add it in the <head> section so that it stays separated from the actual content of your HTML file. But placing it in the <body> can improve loading speed, as the actual website content will be loaded quicker, and only then the JavaScript will be parsed. For this example, let’s take a look at the following HTML file that is supposed to show the current time:
Right now, the above code doesn’t involve JavaScript and hence can’t show the actual time. We can add the following code to make sure it displays the correct time:
We will surround this code by <script> and </script> tags and put it in the head of the HTML code to ensure that whenever the page loads, an alert is generated that shows the current time to the user. Here’s how the HTML file will look after we add the code:
If you want to display the time within the body of the page, you will have to include the script within the <body> tags of the HTML page. Here’s how the code will look when you do so:
Here’s what the final result would look like:

How to Add JavaScript Code to a Separate File
Sometimes adding JavaScript to HTML directly doesn’t look like the best way to go about it. Mostly because some JS scripts need to be used on multiple pages, therefore it’s best to keep JavaScript code in separate files. This is why the more acceptable way to add JavaScript to HTML is via external file importing. These files can be referenced from within the HTML documents, just like we reference CSS documents. Some of the benefits of adding JS code in separate files are:
- When HTML code and JavaScript code is separated, the design principle of separation of concerns is met and it makes everything a lot more sustainable and reusable.
- Code readability and maintenance is made a lot easier.
- Cached JavaScript files improve overall website performance by decreasing the time taken by pages to load.
We can reference the JavaScript file within HTML like this:
The contents of the myscript.js file will be:
Important! Here it’s assumed that the myscript.js file is present in the same directory as the HTML file.
JavaScript Example to Validate an Email Address
JavaScript powers your application by helping you validate user input at the client side. One of the most important user inputs that often need validation is email addresses. This JavaScript function can help you validate the entered email address before sending it to the server:
In order to attach this function to a form input, you can use the following code:
Here’s the result that you would get after combining all the ingredients together in a HTML file:

And if the validation is incorrect, the result will differ:

Congratulations! You have learned how to add JavaScript to HTML with a few basic examples.
Advantages of JavaScript
JavaScript was first known as LiveScript. But because Java was the talk of the town (the world really), Netscape deemed it right to rename it to JavaScript. Its first appearance dates back to 1995 within Netscape 2.0. Here are some of the best advantages of using JavaScript:
Minimalized Server Interaction
It’s a well-known fact that if you want to optimize the performance of a website, the best way is to reduce the communication with the server. JavaScript helps in this regard by validating user input at the client-side. It only sends requests to the server after running the initial validation checks. As a result, resource usage and amount of requests to the server reduces significantly.
Richer, User-Friendly Interfaces
By using JavaScript, you can create interactive client-side interfaces. For example adding sliders, slideshows, mouse roll-over effects, drag-and-drop features and so on.
Immediate Feedback to the User
By using JavaScript, you can ensure that users get an immediate response. For example, let’s imagine a user has filled a form and left one field empty. Without JavaScript validation, they will have to wait for the page to reload only to realize that they left an empty field. However, with JavaScript, they will be alerted instantly.
Easy Debugging
JavaScript is an interpreted language, which means that written code gets deciphered line by line. In case any errors pop up, you will get the exact line number where the problem lies.
Conclusion
In this article, we talked about the two different ways to add JavaScript in HTML code and once you get a hang of things, the possibilities of doing great things by using the two programming languages are endless. JavaScript can be used in combination with HTML to power modern web applications that are intuitive, interactive and user-friendly. By using simple client-side validation, it reduces server traffic and improves the overall efficiency of the website.
Domantas leads the content and SEO teams forward with fresh ideas and out of the box approaches. Armed with extensive SEO and marketing knowledge, he aims to spread the word of Hostinger to every corner of the world. During his free time, Domantas likes to hone his web development skills and travel to exotic places.
Как вызвать функцию JavaScript в HTML
В этом уроке ты узнаешь, как вызывать функции JavaScript с HTML-страниц, чтобы сделать их интерактивными.
HTML и CSS могут структурировать веб страницу и сделать ее красивой. JavaScript помогает веб-странице взаимодействовать с пользователями и направлять их к нужной информации.
Ты можешь использовать функции JavaScript для создания веб-сайтов, которые реагируют на обычные события пользователя, такие как клики, нажатия клавиш, загрузка страницы, наведение курсора мыши.
Я расскажу шаг за шагом о вызове функций JavaScript в HTML, чтобы помочь тебе понять основные концепции веб-разработки с помощью простых в использовании примеров кода.
Использование функций JS с атрибутами событий HTML
Ты можешь использовать атрибуты события в элементе управления HTML для вызова функции Javascript при возникновении события.
HTML предоставляет набор таких атрибутов для охвата широкого спектра событий.
Несколько распространенных примеров — onclick , onchange , onload , onmouseover , onmouseout и onkeydown .
Пожалуйста, имейте в виду, что атрибуты событий HTML работают только с активными элементами управления. Кнопки и ссылки являются немногими примерами таких элементов управления.
Это, пожалуй, самый простой подход для вызова функции JavaScript из HTML-элемента.
Как вызвать функцию JavaScript с помощью атрибутов событий HTML
Давайте разработаем веб-страницу, которая будет принимать имена своих пользователей. Как только пользователь нажмет кнопку “Отправить”, на веб-сайте появится поздравительное сообщение для пользователя.
Мы будем использовать атрибут события HTML “onclick”, чтобы вызвать функцию, когда пользователь нажимает кнопку. Эта функция встретит пользователя предупреждающим сообщением.
Вам нужно будет создать файл HTML и JavaScript, чтобы опробовать этот пример. Давайте создадим index.html для исходного кода HTML и scripts.js для исходного кода JavaScript. Мы также будем использовать эти исходные коды для последующих примеров с минимальными изменениями.
Исходный код HTML
Ты можешь написать или скопировать приведенный ниже исходный код в свой index.html . Этот исходный код HTML показывает текстовое поле и кнопку отправки. Пользователи могут ввести имя в текстовое поле.
В приведенном выше примере используется атрибут события “onclick” в разметке для кнопки “Отправить”. Браузер вызывает функцию “showAlert()”, если пользователь нажимает кнопку “Отправить”.
Исходный код JavaScript
Давайте напишем приведенный ниже исходный код в scripts.js файл —
Эта функция выполняет поиск текстового поля HTML с идентификатором “Полное имя”. Он извлекает вводимые пользователем данные и использует их для отображения сообщения.
Ожидаемые результаты
В действии веб-страница просит конечных пользователей ввести полное имя пользователя. Если вы введете “Джон Коллинз”, система покажет сообщение “Привет, Джон Коллинз!”.
Использование функций JS с обработчиками событий JavaScript
JavaScript предоставляет набор свойств обработчика событий, способных выполнять вызовы функций. Ты можешь использовать их с объектами JavaScript для вызова функций в случае элемента управления HTML.
Каждое из этих свойств соответствует определенному событию. Несколько распространенных примеров — “onload”, “onclick”, “onmouseover”, “onmouseout” и “onkeydown”. Ты можешь получить полный список со многих веб-сайтов в Интернете.
Обработчики событий JavaScript также работают с элементами HTML, не требующими действий. Это означает, что ты можешь превратить даже элемент “
Обработчики событий JavaScript могут вызывать только одну функцию в событии для элемента HTML. Это ограничение, которое прокладывает путь для слушателей событий Javascript, чтобы войти в картину.
Как вызвать функцию JavaScript с помощью обработчиков событий в HTML
Мы разработаем веб-страницу, которая будет принимать имена своих пользователей. Как только пользователь нажмет кнопку “Отправить”, на веб-сайте появится поздравительное сообщение для пользователя.
Здесь мы будем использовать свойство обработчика событий JavaScript “onclick” для вызова функции JavaScript, когда пользователь нажимает кнопку “Отправить”.
Исходный код HTML
Ты можешь написать или скопировать исходный код HTML ниже в свой HTML-документ, index.html . Этот исходный код HTML показывает текстовое поле и кнопку отправки. Пользователи могут ввести имя в текстовое поле.
Исходный код JavaScript
Ты можешь написать или скопировать приведенный ниже исходный код в свой файл JavaScript, scripts.js
В этом примере обработчик событий onclick вызывает функцию showAlert(). Этот вызов функции происходит, когда вы нажимаете кнопку отправки HTML.
Ожидаемые результаты
Если вы введете имя “Джон” и нажмете кнопку “Отправить”, система покажет сообщение — “Привет, Джон!”.
Как использовать слушатели событий для вызова функции JavaScript в HTML
Ты можешь использовать слушатели событий JavaScript для прослушивания событий и вызова функций.
Метод слушателя событий присоединяет слушатель событий к объекту и вызывает нужную функцию при запуске определенного события на объекте.
Это самый мощный, но гибкий подход к вызову функций из HTML.
JavaScript предлагает следующие два метода слушателя событий, которые можно использовать с объектами JavaScript-
- addEventListener() — Добавляет обработчик событий в HTML-элемент и вызывает функции в указанном событии.
- removeEventListener() — Удаляет обработчик событий из HTML-элемента.
Вы должны передать следующие параметры этим методам слушателя событий JavaScript —
- Название события — Вам необходимо передать фактическое имя события HTML DOM. Пример нескольких распространенных событий — щелчок, изменение, фокусировка, перемещение мыши и т.д.
- Имя функции — Вы должны передать здесь имя функции. Браузер вызывает эту функцию в ответ на описанное выше событие на объекте.
- Ты можешь назначить объекту любое количество слушателей событий. Таким образом, ты можешь выполнить несколько вызовов функций в одном событии элемента управления HTML.
Пример кодирования для вызова функции JavaScript с использованием слушателей событий
Мы разработаем веб-страницу, которая будет принимать имена своих пользователей. Как только пользователь нажмет кнопку “Отправить”, на веб-сайте появится поздравительное сообщение для пользователя.
Здесь мы будем использовать слушатель событий JavaScript для вызова функции JavaScript, когда пользователь нажимает кнопку “Отправить”.
Исходный код HTML
Ты можешь написать или скопировать исходный код HTML ниже в свой HTML-документ, index.html . Этот исходный код HTML показывает текстовое поле и кнопку отправки. Пользователи могут ввести имя в текстовое поле.
Исходный код JavaScript
Внешний файл JavaScript, scripts.js должен иметь исходный код ниже —
Когда пользователь нажимает кнопку “Отправить”, браузер выполняет два вызова функций. Это функции “showAlert()` и “Showwelcomemessage()”.
Ожидаемые результаты
Если вы введете Джона в качестве ввода и нажмете кнопку “Отправить”, система должна отобразить два сообщения друг за другом:
How to Call a JavaScript Function in HTML

Once you have a good grasp of HTML and CSS, the next step is JavaScript to take your web projects to the next level. JavaScript adds interactive and dynamic features to web pages — it’s what makes them interesting and engaging beyond just static content.

If you want to make an interactive page, one of the fundamental skills you need to know is how to call JavaScript functions from your HTML document. In other words, when a user engages with an HTML element in some way (like clicking it), how can you trigger a JavaScript function in response?