- How to Call a JavaScript function in HTML
- Using JS functions with HTML event attributes
- How to call a JavaScript function using HTML event attributes
- Using JS functions with JavaScript event handlers
- How to call a JavaScript function using event handlers in HTML
- How to use event listeners to call a JavaScript function in HTML
- A coding sample for calling JavaScript function using event listeners
- Conclusion
- : The Inline Code element
- Try it
- Attributes
- Examples
- Result
- Notes
- Technical summary
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Html code and functions
- Примеры использования
- Глобальные атрибуты
- Ограничения
- Нюансы
- Чем заменить тег
How to Call a JavaScript function in HTML
In this tutorial, you’ll learn how to call JavaScript functions from HTML pages to make them interactive.
The HTML and CSS can structure a web, can give a web its appearance and responsiveness. JavaScript helps a web page interact with users and guide them to the right information. You can use JavaScript functions to build websites that respond to common user events such as clicks, keypresses, page load, mouseover.
We’ll go step-by-step to help you grasp the core Web Development concepts with easy-to-follow code samples.
Using JS functions with HTML event attributes
You can use event attributes in an HTML control to call a Javascript function when an event occurs.
HTML provides a set of such event attributes to cover a wide range of events.
Few common examples — onclick , onchange , onload , onmouseover , onmouseout and onkeydown .
Please bear in mind that HTML event attributes work with actionable controls only. Buttons and links are few examples of such controls.
This is arguably the simplest approach to call a JavaScript function from an HTML element.
How to call a JavaScript function using HTML event attributes
Let’s develop a web page that will accept the names of its users. Once a user clicks the submit button, the website will display a greetings message to the user.
We will use an HTML event attribute onclick , to make a function call when the user clicks the button. This function will greet the user with an alert message.
You will need to create an HTML and a JavaScript file to try out the example. Let’s create index.html for the HTML source code and scripts.js for JavaScript source code. We will use these source codes for later examples too with minimal changes.
The HTML source code
You can write or copy the below source code into your index.html file. This HTML source code shows a text box and a submit button. Users can enter a name in the text box.
html lang="en"> head> title> Calling Function From HTMLtitle> head> body> label for="fullName">Enter your name:label> input type="text" name="fullName" id="fullName" /> button type="submit" onclick="showAlert()"> Submitbutton> script src="/scripts.js">script> body> html>
The above example makes use of onclick event attribute within the markup for submit button. The browser calls showAlert() function if a user clicks the submit button.
The JavaScript source code
Let’s write the below source code in the scripts.js file —
function showAlert() < var name = document.getElementById("fullName").value; alert("Hello " +name +"!"); >
This function searches for an HTML text box with id as “fullName”. It fetches the user’s input and uses that to display a message.
Expected output
When in action, the web page asks end-users to enter the user’s full name. If you enter “John Collins”, the system shows a message, “Hello John Collins!”.
Using JS functions with JavaScript event handlers
JavaScript provides a set of event handler properties capable of making function calls. You can use them with JavaScript objects to call functions in an event of an HTML control.
Each of these properties corresponds to a specific event. Few common examples — onload , onclick , onmouseover , onmouseout and onkeydown . You can get a complete list from many websites on the Internet.
JavaScript event handlers work for non-actionable HTML elements too. This means you can turn even an element into a clickable control using an event handler.
JavaScript event handlers can call only one function in an event for an HTML element. This is a limitation that paves the path for Javascript event listeners to come into the picture.
How to call a JavaScript function using event handlers in HTML
We will develop a web page that will accept the names of its users. Once a user clicks the submit button, the website will display a greetings message to the user.
Here we will use a JavaScript event handler property, onclick to call a JavaScript function when a user clicks the submit button.
The HTML source code
You can write or copy below HTML source code in your HTML document, index.html . This HTML source code shows a text box and a submit button. Users can enter a name in the text box.
html lang="en"> head> title> Calling Function From HTMLtitle> head> body> label for="fullName">Enter your name:label> input type="text" name="fullName" id="fullName"/> button type="submit" id="submitButton"> Submitbutton> script src="/scripts.js">script> body> html>
The JavaScript source code
You can write or copy below source code in your JavaScript file, scripts.js
var bttn = document.getElementById("submitButton"); function showAlert() < var name = document.getElementById("fullName").value; alert("Hello " + name + "!"); > //Used onclick event handler property to call showAlert() function bttn.onclick = showAlert;
In this example, the onclick event handler calls showAlert() function. This function call happens when you click the HTML submit button.
Expected output
If you enter the name “John” and click the submit button, the system shows the message — “Hello Jhon!”.
How to use event listeners to call a JavaScript function in HTML
You can leverage JavaScript event listeners to listen to events and call functions.
An event listener method attaches an event listener with an object and calls the desired function when you trigger a particular event on the object.
This is the most powerful yet flexible approach to call functions from HTML.
JavaScript offers below two event listener methods can be used with JavaScript objects-
- addEventListener() — Adds an event handler to an HTML element and calls functions in a specified event.
- removeEventListener() — Removes an event handler from an HTML element.
You have to pass the below parameters to these JavaScript event listener methods —
- Event Name — You need to pass the actual HTML DOM event name. Example of few common events — click, change, focus, mousemove, etc.
- Function Name — You have to pass the function name here. The browser calls this function in response to the above event on the object.
- You can assign any number of event listeners to an object. Thus, you can make multiple function calls in a single event of an HTML control.
A coding sample for calling JavaScript function using event listeners
We will develop a web page that will accept the names of its users. Once a user clicks the submit button, the website will display a greetings message to the user.
Here we will use a JavaScript event listener to call a JavaScript function when a user clicks the submit button.
The HTML source code
You can write or copy below HTML source code in your HTML document, index.html . This HTML source code shows a text box and a submit button. Users can enter a name in the text box.
html lang="en"> head> title> Calling Function From HTMLtitle> head> body> label for="fullName">Enter your name:label> input type="text" name="fullName" id="fullName"/> button type="submit" id="submitButton"> Submitbutton> script src="/scripts.js">script> body> html>
The JavaScript source code
The external JavaScript file, scripts.js should have below source code —
var bttn =document.getElementById("submitButton"); function showAlert() < var name = document.getElementById("fullName").value; alert("Hello " + name + "!"); > function showWelcomeMessage() < var name = document.getElementById("fullName").value; alert("Welcome, " + name + "!"); > //Event listener method bttn.addEventListener("click", showAlert); bttn.addEventListener("click", showWelcomeMessage);
When a user clicks the submit button, the browser makes two function calls. The functions are, showAlert() and showWelcomeMessage() .
Expected output
If you enter John as input and click the submit button, the system should display two messages back to back:
Conclusion
To sum it up, here are the things you have learned in this tutorial:
- You can use HTML event attributes, JavaScript event handlers to call functions. These can call a single function in a single event of a particular control.
- The HTML event attributes work only with actionable HTML elements.
- The JavaScript event handlers work both with actionable and non-actionable controls.
- JavaScript event listener methods accept HTML DOM events. Thus they give you the flexibility to listen to a wide range of events. In addition to it, they enable you to call many functions in a single event of a control.
- The thumb rule here is, you should use an event handler property when you need to call a single function in an event of a control. In case you need many function calls in a single event, event listener methods are the things you should choose.
Get my free e-book to prepare for the technical interview or start to Learn Full-Stack JavaScript
: The Inline Code element
The HTML element displays its contents styled in a fashion intended to indicate that the text is a short fragment of computer code. By default, the content text is displayed using the user agent’s default monospace font.
Try it
Attributes
This element only includes the global attributes.
Examples
A paragraph of text that includes :
p> The function code>selectAll()code> highlights all the text in the input field so the user can, for example, copy or delete the text. p>
Result
Notes
A CSS rule can be defined for the code selector to override the browser’s default font face. Preferences set by the user might take precedence over the specified CSS.
Technical summary
Content categories | Flow content, phrasing content, palpable content. |
---|---|
Permitted content | Phrasing content. |
Tag omission | None, both the starting and ending tag are mandatory. |
Permitted parents | Any element that accepts phrasing content. |
Implicit ARIA role | No corresponding role |
Permitted ARIA roles | Any |
DOM interface | HTMLElement Up to Gecko 1.9.2 (Firefox 4) inclusive, Firefox implements the HTMLSpanElement interface for this element. |
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 13, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Html code and functions
Тег используется для выделения фрагмента кода, который должен отображаться моноширинным шрифтом и сохранять пробельные символы и переносы строк.
const greeting = 'Привет, мир!';
Примеры использования
Приведём фрагмент кода:
function sum(a, b)
Вы можете объявить переменные с помощью ключевых слов var
, let
или const
.
Используйте <br>
тег, чтобы добавить перенос строки.
НажмитеCtrl+C
, чтобы скопировать.
Используйте<code>
тег, чтобы отобразить код.
Зайдите на сайт https://example.com
.
Для чего использовать тег
- Отобразить фрагменты кода на веб-странице.
- Отформатировать код моноширинным шрифтом с сохранением пробелов и переносов строк.
- Выделить код. Используйте тег с библиотекой подсветки синтаксиса, чтобы показать цветную кодировку синтаксиса.
- Отобразить сочетания клавиш или комбинаций.
- Показать имена переменных, функции или методы.
- Выделить URL-адрес или фрагменты кода, содержащие URL-адреса.
Глобальные атрибуты
Ограничения
Элемент не следует использовать для форматирования текста типографским способом. Тег предназначен для отображения компьютерного кода, а не для обычного текста. Кроме того, не нужно использовать для синтаксиса разметки — вместо него следует использовать элемент .
Нюансы
- Если содержит HTML-элементы < , >или & , то их нужно экранировать с помощью < , > или & .
- Если тег используется для отображения кода с отступом, то пробелы или табуляции, используемые для отступа, могут привести к тому, что код переместится на следующую строку (если элемент контейнера недостаточно широк).
Чем заменить тег
Чтобы отобразить программный код, используйте тег . Однако, если вам нужно отобразить синтаксис разметки или текст, который должен отображаться с форматированием фиксированной ширины, используйте тег .
🔡 Другие теги для изменения текста
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.