Use javascript with html5

How to Use JavaScript in HTML to Create Interactive Webpages

Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

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

JavaScript-in-HTML-to-Create-Interactive-Webpages

  • 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.
Читайте также:  Ассоциативный массив python это

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 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

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

Login

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;

      
Name:


function submitted()

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

script

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.
Читайте также:  Python beautifulsoup xml parsing

#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;

external

  • 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.

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.

Читайте также:  Ucoz свой index html

Check out JavaScript table libraries that you can use today.

Источник

Подключение JavaScript к HTML

Осваивайте профессию, начните зарабатывать, а платите через год!

Курсы Python Ак­ция! Бес­плат­но!

Станьте хакером на Python за 3 дня

Веб-вёрстка. CSS, HTML и JavaScript

Станьте веб-разработчиком с нуля

В этой главе мы займемся размещением сценариев в HTML-документе, чтобы иметь возможность использовать их для оперативной модификации HTML-документа. Для вставки JavaScript-кoдa в НТМL-страницу обычно используют элемент .

Первая программа

Чтобы ваша первая пpoгpaммa (или сценарий) JavaScript запустилась, ее нужно внедрить в НТМL-документ.
Сценарии внедряются в HTML-документ различными стандартными способами:

  • поместить код непосредственно в атрибут события HTML-элемента;
  • поместить код между открывающим и закрывающим тегами ;
  • поместить все ваши скрипты во внешний файл (с расширением .js), а затем связать его с документом HTML.

JavaScript в элементе script

Самый простой способ внедрения JavaScript в HTML-документ – использование тега . Теги часто помещают в элемент , и ранее этот способ считался чуть ли не обязательным. Однако в наши дни теги используются как в элементе , так и в теле веб-страниц.

Таким образом, на одной веб-странице могут располагаться сразу несколько сценариев. В какой последовательности браузер будет выполнять эти сценарии? Как правило, выполнение сценариев браузерами происходит по мере их загрузки. Браузер читает HTML-документ сверху вниз и, когда он встречает тег , рассматривает текст программы как сценарий и выполняет его. Остальной контент страницы не загружается и не отображается, пока не будет выполнен весь код в элементе .

Обратите внимание: мы указали атрибут language тега , указывающий язык программирования, на котором написан сценарий. Значение атрибута language по умолчанию – JavaScript, поэтому, если вы используете скрипты на языке JavaScript, то вы можете не указывать атрибут language .

JavaScript в атрибутах событий HTML-элементов

Вышеприведенный сценарий был выполнен при открытии страницы и вывел строку: «Привет, мир!». Однако не всегда нужно, чтобы выполнение сценария начиналось сразу при открытии страницы. Чаще всего требуется, чтобы программа запускалась при определенном событии, например при нажатии какой-то кнопки.

В следующем примере функция JavaScript помещается в раздел HTML-документа. Вот пример HTML-элемента с атрибутом события, обеспечивающим реакцию на щелчки мышью. При нажатии кнопки генерируется событие onclick.

Внешний JavaScript

Если JavaScript-кода много – его выносят в отдельный файл, который, как правило, имеет расширение .js .

Чтобы включить в HTML-документ JavaScript-кoд из внешнего файла, нужно использовать атрибут src (source) тега . Его значением должен быть URL-aдpec файла, в котором содержится JS-код:

В этом примере указан абсолютный путь к файлу с именем script.js, содержащему скрипт (из корня сайта). Сам файл должен содержать только JavaScript-кoд, который иначе располагался бы между тегами .

По аналогии с элементом атрибуту src элемента можно назначить полный URL-aдpec, не относящийся к домену текущей НТМL-страницы:

На заметку: Подробнее о путях файлов читайте в разделе «Абсолютные и относительные ссылки».

Чтобы подключить несколько скриптов, используйте несколько тегов:

Примечание: Элемент , хотя внешний сценарий выполняется, встроенный код игнорируется.

Независимо от того, как JS-код включается в НТМL-документ, элементы интерпретируются браузером в том порядке, в котором они расположены в HTML-документе. Сначала интерпретируется код первого элемента , затем браузер приступает ко второму элементу и т. д.

Внешние скрипты практичны, когда один и тот же код используется во многих разных веб-страницах. Браузер скачает js-файл один раз и в дальнейшем будет брать его из своего кеша, благодаря чему один и тот же скрипт, содержащий, к примеру, библиотеку функций, может использоваться на разных страницах без полной перезагрузки с сервера. Кроме этого, благодаря внешним скриптам, упрощается сопровождение кода, поскольку вносить изменения или исправлять ошибки приходится только в одном месте.

Примечание: Во внешние файлы копируется только JavaScript-код без указания открывающего и закрывающего тегов .

Расположение тегов

Вы уже знаете, что браузер читает HTML-документ сверху вниз и, начинает отображать страницу, показывая часть документа до тега . Встретив тег , переключается в JavaScript-режим и выполняет сценарий. Закончив выполнение, возвращается обратно в HTML-режим и отображает оставшуюся часть документа.

Это наглядно демонстрирует следующий пример. Метод alert() выводит на экран модальное окно с сообщением и приостанавливает выполнение скрипта, пока пользователь не нажмёт «ОК»:

Источник

Оцените статью