How to add javascript to your website using 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.

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.

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

Adding 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 tag that should encompass all the JS code you write. JS code can be added:

  • between the tags
  • between the 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 section so that it stays separated from the actual content of your HTML file. But placing it in the 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 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 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 to your website using html

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

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

How to add javascript to your website using htmlAnd if the validation is incorrect, the result will differ:

How to add javascript to your website using html

Congratulations! You have learned how to add JavaScript to HTML with a few basic examples.

Final Word

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.

The Author

How to add javascript to your website using html

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.

Responsive web design is about creating web pages that look good on all devices!

A responsive web design will automatically adjust for different screen sizes and viewports.

How to add javascript to your website using html

What is Responsive Web Design?

Responsive Web Design is about using HTML and CSS to automatically resize, hide, shrink, or enlarge, a website, to make it look good on all devices (desktops, tablets, and phones):

Setting The Viewport

To create a responsive website, add the following tag to all your web pages:

Example

This will set the viewport of your page, which will give the browser instructions on how to control the page’s dimensions and scaling.

Here is an example of a web page without the viewport meta tag, and the same web page with the viewport meta tag:

Tip: If you are browsing this page on a phone or a tablet, you can click on the two links above to see the difference.

Responsive Images

Responsive images are images that scale nicely to fit any browser size.

Using the width Property

If the CSS width property is set to 100%, the image will be responsive and scale up and down:

How to add javascript to your website using html

Example

How to add javascript to your website using html

Notice that in the example above, the image can be scaled up to be larger than its original size. A better solution, in many cases, will be to use the max-width property instead.

Using the max-width Property

If the max-width property is set to 100%, the image will scale down if it has to, but never scale up to be larger than its original size:

How to add javascript to your website using html

Example

How to add javascript to your website using html

Show Different Images Depending on Browser Width

element allows you to define different images for different browser window sizes.

Resize the browser window to see how the image below change depending on the width:

How to add javascript to your website using html

Example

How to add javascript to your website using html

Responsive Text Size

The text size can be set with a “vw” unit, which means the “viewport width”.

That way the text size will follow the size of the browser window:

Resize the browser window to see how the text size scales.

Example

Viewport is the browser window size. 1vw = 1% of viewport width. If the viewport is 50cm wide, 1vw is 0.5cm.

Media Queries

In addition to resize text and images, it is also common to use media queries in responsive web pages.

With media queries you can define completely different styles for different browser sizes.

Example: resize the browser window to see that the three div elements below will display horizontally on large screens and stacked vertically on small screens:

Example

Tip: To learn more about Media Queries and Responsive Web Design, read our RWD Tutorial.

Responsive Web Page – Full Example

A responsive web page should look good on large desktop screens and on small mobile phones.

Responsive Web Design – Frameworks

All popular CSS Frameworks offer responsive design.

They are free, and easy to use.

W3.CSS

W3.CSS is a modern CSS framework with support for desktop, tablet, and mobile design by default.

W3.CSS is smaller and faster than similar CSS frameworks.

W3.CSS is designed to be a high quality alternative to Bootstrap.

W3.CSS is designed to be independent of jQuery or any other JavaScript library.

Resize the page to see the responsiveness!

London

London is the capital city of England.

It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.

Paris

Paris is the capital of France.

The Paris area is one of the largest population centers in Europe, with more than 12 million inhabitants.

Tokyo

Tokyo is the capital of Japan.

It is the center of the Greater Tokyo Area, and the most populous metropolitan area in the world.

When you can’t use a JavaScript or CSS concatenater, this method can be useful for adding scripts and styles to your site on the fly.

This is how we typically add JavaScript and CSS files to websites:

The Ideal Scenario

But, as your site gets super awesome, it can also get super cluttered. For example, with stylesheets, you’re either going to have a giant, messy stylesheet, or (preferably) you’re going to have a handful of (let’s hope) nicely-organized stylesheets. The downside to that is the section of your HTML markup is going to get messy. That’s not to mention that every request for a file, like a stylesheet, takes time and resources, and will slow your site down.

Ideally, you should compile these files into a single, manifest file. There are plenty of tools out there to help you with this. Compass and Gulp are a couple examples.

And if you’re using a server-side language to build your site (something like Ruby or PHP), you have even more tools available to you.

Doing It On The Client Side (JavaScript)

If you can’t make the ideal scenario happen, an okay option is to add these scripts and styles via a single script.

To do so, add something like this to the of your document (hopefully you have a single master page or header file, so you only have to do this once):

You’ll want to add this to the end of your section, so it is the last script loaded.

Note: There is a small chance of introducing an errors using this method. Because your scripts are being loaded in your head instead of at the end of your body, your page may not load if there is a JavaScript error. Also, be aware that other JavaScript files may be loaded after this if they are either loaded dynamically or are loaded at the end of the body.

Now, in your controller.js file, add this function:

Below that function (in controller.js) you can call all your JS and CSS files, like so:

Now your files should load no problem!

Using jQuery

A somewhat cleaner method is to write the same function using jQuery. To do so, your document would need this markup:

Notice here we’re loading the jQuery library first, so we can use it in controller.js . I’m loading this library from Google Libraries, but you can certainly add it however you’d like.

Now, in the controller.js file:

And you would add your files in the same manner as before.

As you can see, this is much cleaner, but unless you’re planning to use the jQuery library throughout your JS code, it’s not worth loading the entire library for this one function.

Load Order

You can’t always be sure how your browser is going to handle the load order of your scripts. If you’re scripts have interwoven dependencies, then you may consider using a tool like RequireJS to ensure your scripts are loaded in the appropriate order.

References:

Want to receive approximately one email every month with new articles, tools, and references I’ve discovered? Sign up below.

This site was created and is maintained by Sean C Davis. It was designed by Matt Willett.

The stack is Eleventy, Tailwind CSS, and loads of other open-source software. The code is built, deployed, and hosted with help from GitHub and Netlify.

Website Builder позволяет вставлять на веб-сайт собственный код (HTML, CSS и JavaScript). Таким образом вы можете расширять функции своего ресурса, добавляя на него дополнительные объекты, например карты, формы и кнопки.

Добавьте Google Аналитику, Пиксель Facebook, Метатег Facebook, Метатег Pinterest и Google AdSense напрямую на свой сайт в Настройках. Раздел настраиваемого кода не требуется. Убедитесь, что вы разрешили посетителям сайта устанавливать настройки cookie и отслеживания. Это требуется в рамках законодательства.

Примечание. Вставляйте код, только если знаете, что делаете, так как это может повлиять на работу всего сайта. Поэтому используйте его только в том случае, если вам удобно писать код вручную или у вас есть конкретный код с другого сайта.

  1. В аккаунте GoDaddy откройте страницу продукта.
  2. Прокрутите до Website Builder и выберите Управление рядом со своим веб-сайтом, чтобы открыть его.
  3. Чтобы открыть конструктор сайтов, выберите Редактировать веб-сайт или Редактировать сайт.
  4. Откройте страницу, на которой хотите разместить настраиваемый код, и добавьте раздел.
  5. Найдите раздел HTML и выберите Добавить.
  6. Вставьте или напишите свой собственный код в поле Настраиваемый код.
  7. Настройте остальные части раздела, например цвет акцента, заголовок, переключатель выравнивания по центру и высоту. Оставьте поле Принудительная высота пустым для автоматического увеличения или установите конкретную высоту в пикселях. Высота 0 пикселей эквивалентна удалению раздела.
  8. Изменения сохраняются автоматически. Чтобы увидеть результаты, используйте предварительный просмотр. Когда все будет готово, опубликуйте свой сайт.

Website Builder позволяет вставлять на веб-сайт собственный код (HTML, CSS и JavaScript). Таким образом вы можете расширять функции своего ресурса, добавляя на него дополнительные объекты, например карты, формы и кнопки.

Добавьте Google Аналитику, Пиксель Facebook, Метатег Facebook, Метатег Pinterest и Google AdSense напрямую на свой сайт в Настройках. Раздел настраиваемого кода не требуется. Убедитесь, что вы разрешили посетителям сайта устанавливать настройки cookie и отслеживания. Это требуется в рамках законодательства.

Примечание. Вставляйте код, только если знаете, что делаете, так как это может повлиять на работу всего сайта. Поэтому используйте его только в том случае, если вам удобно писать код вручную или у вас есть конкретный код с другого сайта.

  1. В аккаунте GoDaddy откройте страницу продукта.
  2. Прокрутите до Website Builder и выберите Управление рядом со своим веб-сайтом, чтобы открыть его.
  3. Чтобы открыть конструктор сайтов, выберите Редактировать веб-сайт или Редактировать сайт.
  4. Откройте страницу, на которой хотите разместить настраиваемый код, и добавьте раздел.
  5. Найдите раздел HTML и выберите Добавить.
  6. Вставьте или напишите свой собственный код в поле Настраиваемый код.
  7. Настройте остальные части раздела, например цвет акцента, заголовок, переключатель выравнивания по центру и высоту. Оставьте поле Принудительная высота пустым для автоматического увеличения или установите конкретную высоту в пикселях. Высота 0 пикселей эквивалентна удалению раздела.
  8. Изменения сохраняются автоматически. Чтобы увидеть результаты, используйте предварительный просмотр. Когда все будет готово, опубликуйте свой сайт.

Emoji’s first appeared in 1997 on Japanese mobile phones. They are the descendants of the Emoticons; which are those basic text-based imitation of emotions 😉 – Yes, this is an actual example.

Emoji’s grew in popularity years after years by being included in more and more computer, mobile devices, applications, games etc. They are so popular nowadays that they account for a part of the popular culture.

We are using those communication helpers, especially in the younger generations. But how do they work? To stay light, let’s say that Emoji’s are characters; very much like letters, punctuation marks or symbols.

Can you find this movie?

How did I integrate those Emoji’s into my article? How could I do it anywhere on the web?

We will see different techniques available in HTML, CSS and JavaScript. They rely on two methods; copy-pasting and codepoint.
First find your Emoji, then follow the steps in the language you want.

The most straightforward way. You can paste the previously chosen Emoji.

Exit fullscreen mode

Your other option is to use the codepoint of the Emoji and replacing U+ with &#x .

Exit fullscreen mode

In CSS you need to use the ::before or ::after pseudo-element coupled with the content property where you paste the Emoji as the value.

Exit fullscreen mode

The same way, you can use codepoint replacing U+ with \0 .

Exit fullscreen mode

JavaScript

In JavaScript you need to specify the innerHTML by pasting the Emoji.

Exit fullscreen mode

Similarly, you can use the String method fromCodePoint mixed with the codepoint value where you replace U+ with 0x .

Exit fullscreen mode

Live example on Codepen

Isn’t an example worth a million words? ?

All major Browsers support the Emoji’s so there is no excuse.
Try it yourself and use Emoji’s all over the web!

Keep playing to learn! ?

If you find value in what I offer don’t hesitate and buy me a coffee ?

The movie described with Emoji’s is E.T.

Note: There are plenty of options to have Emoji’s integrated that I am not covering in this article. Icon fonts or SVG’s are examples, it’s up to you to decide what you will use.

Summary

Many Internet Web sites contain JavaScript, a scripting programming language that runs on the web browser to make specific features on the web page functional. If JavaScript has been disabled within your browser, the content or the functionality of the web page can be limited or unavailable. This article describes the steps for enabling JavaScript in web browsers.

More Information

Internet Explorer

To allow all websites within the Internet zone to run scripts within Internet Explorer:

On the web browser menu, click Tools or the “Tools” icon (which looks like a gear), and select Internet Options.
How to add javascript to your website using html

When the “Internet Options” window opens, select the Security tab.

On the “Security” tab, make sure the Internet zone is selected, and then click on the “Custom level. ” button.
How to add javascript to your website using html

In the Security Settings – Internet Zone dialog box, click Enable for Active Scripting in the Scripting section.
How to add javascript to your website using html

When the “Warning!” window opens and asks, “Are you sure you want to change the settings for this zone?” select Yes.

Click OK at the bottom of the Internet Options window to close the dialog.

Click the Refresh button to refresh the page and run scripts.
How to add javascript to your website using html

To allow scripting on a specific website, while leaving scripting disabled in the Internet zone, add the specific Web site to the Trusted sites zone:

On the web browser menu, click Tools, or the “Tools” icon (which looks like a gear) and select Internet Options.
How to add javascript to your website using html

When the “Internet Options” window opens, select the Security tab.

On the “Security” tab, select the Trusted sites zone and then click the Sites button.
How to add javascript to your website using html

For the website(s) you would like to allow scripting, enter the address within the Add this website to the zone text box and click Add. Note: If the address does not begin with “https:”, you many need to uncheck “Require server verification (https:) for all sites in this zone”.
How to add javascript to your website using html

Click Close and then click OK at the bottom of the Internet Options window to close the dialog.

Click the Refresh button to refresh the page and run scripts.
How to add javascript to your website using html

Google Chrome

To enable JavaScript in Google Chrome, please review and follow the instructions provided at Enable JavaScript in your browser to see ads on your site.

Mozilla Corporation’s Firefox

To enable JavaScript in Firefox, please review and follow the instructions provided at JavaScript settings for interactive web pages.

Navigation

Site search

Site navigation

JavaScript tutorial

  • Important guidelines
  • Introduction to JavaScript
  • Examples
  • Adding JavaScript to a page
  • Object oriented programming
  • Operators
  • Variables
  • Control structures
  • Writing with script
  • Writing functions
  • Referencing
  • Browser inspecific referencing
  • Browser specific referencing
  • DHTML
  • Element contents
  • Window size and scrolling
  • Event information
  • Creating objects
  • Creating time delays
  • Using cookies
  • Security
  • Semicolons
  • The JavaScript object
  • W3C DOM introduction
  • DOM nodes and tree
  • DOM tables
  • DOM CSS
  • DOM Style Sheets
  • DOM events
  • DOM objects and methods

Printing

  • View tutorial as a single document
  • Print styling information
  • Printing policy

Other tutorials

  • CSS tutorial
  • HTML tutorial
  • Site design

Adding JavaScript to a page

You can add a script anywhere inside the head or body sections of your document. However, to keep your document well structured there are some basic guidelines:

  • Most scripts can go inside the document head. This keeps them out of the way of the main document content.
  • If your script needs to run at a certain stage during page layout (for example, if it uses document.write to create content), it should be put at the correct stage of the document, almost always somewhere inside the document body. If the script is very small, then put it all where it will be used. If it is larger, then put it inside the head inside a function, and you can then call that function when you need it.
  • If your script is used on more than one page, or if it is of any significant size, then put it in its own file, and load it in the document head. Not only will this help to keep the clutter of the document, but it will also help avoid potential syntax problems (I will cover these later). As an extra benefit, these can be used by multiple pages, allowing browsers to use their cache, and saving bandwidth for you and your visitors.

Adding a script to the page

To insert JavaScript into a web page, use the

If your script is incapable of providing its own fallback, but it is needed to access the page, you should include support for non-JavaScript browsers by using:

Using comments

Comments allow you to leave notes to yourself and other people in your script, and are useful as a reminder of what the script is doing and why. The double slash indicates a single line comment. Everything after it on the same line will be ignored by the script engine. The slash-asterisk indicates a block comment. Everything after it will be ignored by the script engine until an asterisk-slash is encountered.

Using external script files

You can also use a separate header file to contain the JavaScript (usually *.js) making it easy to share across pages:

When using header files, if you put any script code in between the tags, it will only be executed if the browser does not support header files (assuming it does support the version of JavaScript shown in the language attribute, if you used one). In reality, this is only for very old browsers that are not used at all any more, so there is no need for anything to be put there.

Scripts in header files are executed as if they were in the main page. If the script referances any external files, such as images, the addresses it uses are relative to the main page, not the script URI.

Commenting out your scripts

This is not needed any more. All current browsers are aware of script tags, and how to treat their contents, since they have been part of HTML since HTML 3. Browsers that do not understand HTML 3 or scripts (these are virtually never used now) will display the script as if it was the content of the page. You can hide the script from them by commenting out your script with standard HTML comments. Browsers that understand script will simply ignore these comments, and will just interpret the script within them. The opening comment is ignored as if it were a normal single line JavaScript comment. The closing comment will not, so it needs to have a JavaScript comment put before it:

These HTML comments should not be used if you are using an external script file, and are not to be used anywhere else in your scripts.

Dealing with XHTML

Note that when I talk about XHTML, I am talking about pages that are served using a content type of application/xhtml+xml – the majority of pages that use XHTML markup are actually served as text/html and as a result are correctly treated as HTML, not XHTML.

The rules in XHTML are different. Script tags are not treated as being special. Their contents are treated as any other part of XHTML, so various operators can be misinterpreted as part of the markup. To avoid this, it is best to put all scripts in external script files so that they do not interfere with the page itself. If you feel the need to put something directly on the page, you can declare it as CDATA (the default for script contents in normal HTML):

If you feel the compulsion to comment out your script in XHTML, you must use a more ugly structure to contain your scripts. Again, this really is not needed, since browsers that do not understand script also do not understand XHTML, but in case you want to use it (maybe you are serving it as XHTML to some browsers, and HTML to others), this is what to use:

Controlling when the script is activated

By default, any script you write will be processed as the document loads. For example:

Sometimes, this may be undesirable and it may be better to write functions (see the section on Writing functions) and activate them later.

To activate JavaScript, you can use HTML events. Modern browsers can detect a vast number of events on most elements. Older browsers are more limited and can only detect the standard set of events on specific elements. The ones that will work in all browsers I have tested are:

input, textarea, select onclick, onkeydown, onkeyup, onkeypress, onchange, onfocus, onblur, etc. form onsubmit, onreset a onclick, onmouseover, onmouseout, onfocus, onblur body onload, onunload

Check with the HTML specifications on the W3C site for more details. ‘a’ elements can also detect onmousemove in all current browsers, but not some of the older browsers that are not used any more. For some of these older browsers, such as Netscape 4, it is possible to compensate using a combination of onmouseover, onmouseout and then document.captureEvents and onmousemove on the body (see the section on Event information). The Event information and more advanced DOM events chapters of this tutorial show how to listen for more event types, and obtain information from them.

These are some examples of using events (shown here using traditional inline event handlers – later on in this tutorial, I will show you alternative ways to attach events to elements that will not require you to alter your HTML):

In all these cases, the script is contained within HTML attributes, and is subject to the normal rules of HTML entities. If you need to put quotes in the script in between the quotes in the html, use the HTML entity ” or ” for ” style quotes or if your quotes in the HTML are done using the ‘ quotes (which is unusual . ), you can use ‘ to represent these in the script. If you need to include operators, you should use the entities.