Extending HTML with JavaScript

<!DOCTYPE html>
<html>
<head>
<title>HTML and JavaScript</title>
</head>
<body>
	<p onclick="JavaScript:alert('Hey thanks!');">Click me!</p>
</body>
</html>

Above is a basic example of JavaScript in an HTML document. When you click the contents of the <p> element, some JavaScript runs.

What Is JavaScript?

JavaScript is a scripting language that can be used to extend your HTML documents. It uses programming concepts such as conditional statements, loops, and functions to provide potentially complex applications.

JavaScript allows you to add interactivity to your web pages. Using JavaScript, you can create drop down menus, add validation to your forms, display the date, and much more.

Why Use JavaScript?

JavaScript can be used for any functionality that can't be provided by HTML alone. While it's true that it could be used instead of HTML for many things, it's usually better to use HTML for those things that HTML can do. In other words, only use JavaScript if HTML can't do it.

Here are some examples of where JavaScript can come in handy:

  • Advanced menus (eg, drop–down menus, slide–out menus, etc).
  • Client-side form validation. Ensures the user has completed a form correctly before it's submitted to the server.
  • Setting cookies. This could assist in your website "remembering" its users' preferences, or which pages they viewed during their last visit, etc.
  • AJAX applications. You could use client-side JavaScript to communicate with a server-side script in order to pull data from a database based on the user's selection. A single part of the page can be updated without needing to refresh the whole page (which would normally need to be done when pulling data from the server). For example, if the user selects their country on a form, JavaScript could be used to dynamically populate the Region field with only those regions from the selected country. The Region data could come from a database on the server.
  • Displaying ads. Most ad networks provide publishers with a snippet of JavaScript that they can add to their page in order to display ads from the ad network. The ad network can display the most appropriate ad for the user based on their preferences, previous websites visited, previous ads clicked on, what they've searched for in the past, etc. This of course, assumes that the ad network has access to that data. Large networks like Google usually have this information due to their wide-spread presence on the web.
  • Page analytics. JavaScript code can be added to your website which can track your visitors' movements on your site, such as how many visitors, the pages they visited, how long they spent on your site, etc.
  • And much more…

Integrating JavaScript with HTML

There are a three main ways to incorporate JavaScript into your HTML documents; inline, embedded, and external.

Inline

In the above example we place the Javascript directly within the HTML element. We do this using the onclick event handler content attribute, like this:


<p onclick="JavaScript:alert('Hey thanks!');">Click me!</p>

Embedded

You can also place JavaScript between <script> tags. You could write multiple lines of JavaScript code and as long as it is surrounded by <script> tags, it will run (as long as it doesn't have any bugs!).

Using this method, we could create our own function, then place the JavaScript code inside that function. The function won't run until a particular event is triggered. We choose that event by using an event handler content attribute (eg, the onclick event handler).

In the following code example, we place a JavaScript function in <head> and call that function from within the HTML code.


<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
<script type="text/javascript">
	function myFunction() {
		// JavaScript goes here...
	}
</script>
</head>
<body>
	<p onclick="JavaScript:myFunction();">Click me!</p>
</body>
</html>

External JavaScript Files

HTML also provides the ability to link to an external JavaScript file (rather than include the code within the HTML document). This way, you can place all JavaScript code in a different file (usually with a .js extension). This allows you to keep your JavaScript code separate from your HTML code and it saves the HTML document from becoming too long. Usually, the longer your HTML document is, the harder it is to update.

Another benefit of using an external JavaScript file is that browsers will often cache external files. In other words, the browser will save a copy of the file locally, and it won't need to download it again every time the user requests another page from your website (assuming those pages also link to the same JavaScript file). This saves bandwidth and can speed up your page for visitors who visit more than one page as well as returning visitors. This is because the JavaScript file is still stored locally in their browser—it doesn't need to be downloaded every time the visit a page on your website.

Now, if all your JavaScript code was embedded into your HTML document (i.e not in an external JavaScript file), every time your users visit a new page on your website, all that JavaScript would need to be downloaded again. If you have lots of JavaScript, this could increase the page download time quite considerably.

Having said this, there are times where embedding JavaScript directly into the HTML can be better for performance. This is especially true if you have many external JavaScript files. Each external file that needs to be downloaded can add a little bit more time to the download.

Event Handler Content Attributes

Regardless of which method you use, you will almost always trigger the JavaScript the same way; using an event handler content attribute.

These are the connection between your HTML code and the JavaScript code. They enable you to specify exactly when the JavaScript will run, instead of it simply running as soon as the page loads. That said, you may in fact wish for some JavaScript to run as soon as the page loads. This is fine. You can do that too. It's just that, in most cases, you will only want a script to run upon a given event (like a user clicking on an element, etc).

Client-Side vs Server-Side

JavaScript is usually run on the client-side—it runs in the user's browser (or other user agent). This means that the JavaScript code is downloaded once, when the user requests the page, and it then runs from the user's side. Although it is only downloaded once, it could run many times throughout the user's session. And different parts of the script could be triggered depending on what the user does during their session.

This is in contrast to a script that runs on the server-side. A server-side script is not downloaded to the user's computer. Instead, it runs on the server. Examples of server-side scripting languages include PHP, ColdFusion, Python, ASP. Actually, JavaScript can also run on the server, but it is most commonly used client-side.

Client-side scripts tend to feel much quicker and more responsive than server-side scripts. This is because there's no need to call the server like a server-side script would need to do. The client-side script runs in the browser and the browser responds instantly. Calling a server-side script usually feels slower (even if the server-side script runs blisteringly fast on the server) because of the latency between the client and the server—the user's request must travel across the internet to the server, then once the script has run on the server, the result must travel back across the internet to the user. Although this may only take a second or so, a second can feel like a long time—especially when client-side scripts will usually respond within milliseconds.

Despite the benefits of client-side scripting, server-side scripting is an essential part of web development. Most modern websites will have a combination of client-side scripting and server-side scripting. Server-side scripts can process forms, query databases, implement security measures, and much more that you wouldn't (and/or couldn't) do on the client-side.

But let's not get ahead of ourselves. The main thing to remember from this page is that you can easily extend your HTML documents with client-side JavaScript. And that HTML allows this via the <script> element and event handler content attributes.

About HTML.am

HTML.am was created in order to provide HTML tools, codes, tutorials, and other resources to help webmasters create and maintain their HTML documents.

HTML.am aims primarily at beginners, but may also be useful to web professionals.

About the HTML Codes

The HTML codes on this website are provided free of charge, for you to use however you wish. Feel free to modify the code to suit your own needs.

Need Hosting?

Our partner site ZappyHost provides website hosting, domain names and related products at some of the best prices on the web. If you need web hosting, check them out!