HTML Scripts

Chapter 16 26 mins

Learning outcomes:

  1. What are scripts in HTML
  2. What is JavaScript?
  3. The <script> element
  4. Event attributes in HTML
  5. The <noscript> element

What are scripts?

If we go, once again, back in time when HTML was first introduced to the world, we see that there was absolutely no concept of scripting in it then.

But what is scripting?

Well, from the perspective of HTML:

Scripting refers to a creating small pieces of programs, referred to as scripts, that are executed by the browser to power certain features on HTML documents.

In other words, back in the day, HTML was purely just static without any capability whatsoever to add interactivity to HTML documents. Simple and straight, but clearly mundane.

But as the web grew in complexity, many people began to feel the need of scripting on the web to be able to perform common tasks directly within the browser, instead of having to offload them to the server.

For example, one such task was validating an input field for a correct value. To date, input validation remains a useful aspect of web development.

The straightforward approach back then was to submit the underlying form to the server which would then validate the fields and return an appropriate response. However, as you may agree, responding to the user after a while just to inform that he/she has left a field empty doesn't make sense — such a simple task should be able to be done right within the browser.

Note that this was just one instance of the increasing desire to bring scripting to the web; there were many others.

Ultimately, HTML 4.0 brought the notion of scripting to HTML.

Now, for scripting a webpage, we need something called a scripting language.

A scripting language is used to create a script, i.e. a small program, that's executed by the browser.

To be slightly more specific, a script is executed by the scripting language's engine in the browser, which is essentially just another compute program.

So, in that sense, a scripting language is a programming language that's executed by another computer program. That's why we call it a scripting language, i.e. is used to write 'scripts' that are read and understood by another program.

Initially, akin to style sheets, HTML went with the possibility of there being many possible scripting languages added to the web, and likewise created features to be able to facilitate this possibility.

For instance, some popular scripting languages during this era were JavaScript, JScript (developed by Microsoft for Internet Explorer; essentially a variant of JavaScript), VBScript, and Tcl.

However, the most naive of all of these was JavaScript.

Let's learn more about it...

What is JavaScript?

Amongst its many features, Netscape Communications in their Netscape Navigator 2.0 browser released a new scripting language which we today know of as JavaScript.

JavaScript is a scripting language used to make HTML documents dynamic and interactive.

JavaScript was conceived to be a superbly simple language.

Initially it had very few rules, few data types, few technicalities, and was intended for a wide range of audiences, including non-technical people, such as authors, designers, researches, etc. to add nice interactive features to their webpages.

Despite the fact that, for quite some time, interactions were possible on the web, all resorted to some pretty technical languages, such as Java or VBScript.

JavaScript intended to revolutionize this by providing a ubiquitous language to work with on the web, most importantly not requiring a lot of — in fact, any — prior programming knowledge.

It started off with very simple and elementary features — like events, a few data types, a very basic language model, and so on — and all those features soon gained traction.

Eventually, JavaScript gained popularity over all other scripting languages, even the mammoth Java programming language, and eventually became the only supported scripting language in HTML. Browsers deprecated the usage of other scripting languages, for the purposes of brevity and reducing browser complexity.

With time, JavaScript acquired notable bells and whistles, to shift from a language capable of only a few things in the web to one that could handle an exceptionally diverse set of concerns.

Today, JavaScript is completely different to what is conceived of back then. Few would have imagined that such a simple language would survive in the coming years, and not just survive but thrive.

We could continue talking about it for an hour or so, but we'll try not to. That's because we're more concerned with learning HTML for now while only exploring its related technologies on their outskirts.

Once we're done with HTML, and then with CSS (yet another major technology), it's precisely then that we'll devote a large part of our time to exploring JavaScript in great depths.

To get an overview of how huge JavaScript actually is, you can consider viewing the table of contents of our JavaScript course — it should give you a really good estimate.

However, just for some element of excitement of it, we'll quickly go through a couple of concepts from JavaScript to add some level of interactivity to our HTML documents.

But first we need to know where to put JavaScript in HTML. Right?

The <script> element

To include some JavaScript code on an HTML document, we have three ways. Of these three ways, two utilize the HTML <script> element.

In this section we aim to discuss more about <script>.

The <script> element is used to represent a script in HTML.

<script> can appear either inside the <head> element or the <body> element in HTML, or even in both. And we can have as many <script>s in a document as we want to.

If we have an external JavaScript file, with the .js extension, it's linked to by the <script> element via its src attribute.

Otherwise, if we don't have an external JavaScript file, our JavaScript code goes directly inside the <script> element.

Let's see each of these in more detail...

External JavaScript file

JavaScript code, just like CSS code, can be placed in a separate, external file. Such a file has a .js extension at its end to signifiy that it's a JavaScript file.

Unlike an external style sheet, an external script isn't linked to an HTML document via the traditional <link> element; instead, it's linked to using the <script> element and that via its src attribute.

The attribute specifying the address of the linked JavaScript file in the <script> element is named src, NOT href (as is otherwise the case with <link>).

Let's consider an example.

Below we have a simple HTML document with an <h1> and <p> element:

<h1>Working with scripts</h1>
<p>This is a paragraph.</p>

In the following discussion, our goal will be to add a click handler to the <p> element so that when we click it, we get a the alert message 'Hello World!' shown to us.

But obviously, first we need to understand some of the concepts of JavaScript that'll be used to implement this. And that's what we do in the following snippets, one by one.

Selecting an HTML element by its id attribute

Let's start off with selecting an element using its id attribute.

Selecting an element in JavaScript means to access it programmatically so that we're able to perform certain actions on it, like changing its content, altering its styles, etc.

There are a multitude of ways of selecting HTML elements in JavaScript but the most simplest would be to use the document.getElementById() method.

  • document here represents the entire underlying HTML document (where the given script is running).
  • The . means that we're about to use some property of the preceding value document, in JavaScript.
  • getElementById() is a function (under document) that selects an element from the document that has a given id attribute value. The attribute's value goes within the pair of parentheses (()), enclosed in quotes, single ('') or double ("").

After completion, document.getElementById() returns back a programmatic representation of the selected HTML element (if there's any with the given id).

For example, in the code below, we select the <p> element:

<p id="p1">This is a paragraph.</p>

Using this returned value, we can do anything with the HTML element.

One of the most common of these is to add an event handler to the element. The next snippet discusses about this.

Events and event handlers

An event is simply an action that occurs on a webpage.

For example, clicking on an element in an HTML document is an event. So is scrolling the document. So is hovering the mouse over the document. So is loading the HTML document completely. And the list goes on and on and on.

JavaScript allows us to tap into these events, as they occur on a webpage, and get some reactions to be made.

For example, upon the click of an element, we might want to change the content of the HTML document, or maybe change the styles of the element, or produce alert messages, etc.

The naive way to tap into events in JavaScript is by using event handler properties of HTML elements.

As an instance, click denotes an event on a webpage that simply represents a click — a mouse click; the corresponding event handler property in JavaScript is called onclick. This property is available on the value returned by document.getElementById().

So following the example above, we can assign a function to the onclick property of the element returned by document.getElementById(), as shown below:

document.getElementById('p1').onclick = function() {
   alert('You just clicked the paragraph.');

A function is a block of statements that represent a particular procedure, an action.

Here, the function simply alerts a message using JavaScript's predefined function alert().

The alert() function

The alert() function is a predefined function in JavaScript that serves to make an alert message in the browser window.

The message that has to be written in the alert box is provided to the function within the pair of parentheses (()), enclosed in single quotes ('') or double quotes ("").

In the example above, restated as follows:

document.getElementById('p1').onclick = function() {
   alert('You just clicked the paragraph.');

we alert the text 'You just clicked a paragraph.' when the shown <p> element is clicked.

Now that we know a little bit about some ideas from JavaScript, let's get to our task.

First off, since we need to select the <p> element, we'll give it an id. Let's call it "p1":

<h1>Working with scripts</h1>
<p id="p1">This is a paragraph.</p>

Next off, we need to write our JavaScript. For this, we'll add a <script> element at the end of the <body> element:

<h1>Working with scripts</h1>
<p id="p1">This is a paragraph.</p>


Note that, for this example, it's mandatory to have the <script> element come after the <p> element in the HTML.

Why? Because our JavaScript code needs access to the <p> element which is only possible once the <p> element is already seen by the browser before executing a script.

In this example, we'll be linking to an external JavaScript file using <script>; let's name it script.js. It'll exist in the same directory where the HTML file exists.

Below, we link to this file in our <script> element, using its src attribute:

<h1>Working with scripts</h1>
<p id="p1">This is a paragraph.</p>

<script src="script.js"></script>

The last thing left to do is to create the script.js file and put some JavaScript code in it. Let's do that now:

document.getElementById('p1').onclick = function() {
   alert('Hello World!');

Time to see the output:

Live Example

Go on, open the document linked above, and click on the <p> element in there; you'll get an alert message as you do so.


Internal script

Apart from including a separate JavaScript file in an HTML document via the src attribute of the <script> element, we can put the JavaScript code directly inside the element.

This is really handy when we want to have specific pieces of scripts for specific documents in a website, or when having a whole file would be way too much for just a simple line of JavaScript code.

Below we demonstrate an example.

Here's the same HTML document that we had above, along with the <script> element but with its src attribute removed:

<h1>Working with scripts</h1>
<p id="p1">This is a paragraph.</p>


The purpose of removing the src attribute is because we'll be writing our script directly inside the element.

Now, let's add the code inside the element:

<h1>Working with scripts</h1>
<p id="p1">This is a paragraph.</p>

document.getElementById('p1').onclick = function() {
alert('Hello World!');
}; </script>

The output produced would be exactly the same as before:

Live Example

HTML event attributes

There's a third way to add JavaScript code to an HTML document and that's by using HTML event attributes.

The value of an event attribute in HTML is a script, i.e. JavaScript code, which executes whenever the underlying event occurs on the element.

These attributes are named akin to event properties in JavaScript, like the onclick property we saw above. And just like in JavaScript, there is a humongous collection of these attributes in HTML.

Let's try replicating the example above using the onclick HTML attribute.

Here's our HTML document:

<h1>Working with scripts</h1>
<p>This is a paragraph.</p>

First off, notice that we've removed the id attribute from the <p> element. That's because now we don't need to select the element in a separate script in the HTML document to add a click handler to it; we'll be adding an event attribute directly to the element in the HTML.

Recall that our task was to show an alert, reading 'Hello World!', when the <p> is clicked.

To do so, we'll use the HTML onclick attribute on <p> and set its value to a piece of JavaScript code that we want executed when the element is clicked.

Something as follows:

<h1>Working with scripts</h1>
<p onclick="alert('Hello World!')">This is a paragraph.</p>

Let's see the output produced:

Live Example

Just as we desired.

The <noscript> element

Almost all modern-day browsers give users the option to disable JavaScript while viewing a particular website.

When this choice is selected — that is, when JavaScript is disabled — all <script> elements becomes useless. Simply, no JavaScript code is executed by the browser.

This might be an issue for a website that relies heavily on JavaScript for numerous functionalities. In fact, some websites depend on JavaScript from the ground up — if it's disabled, there's absolutely no content on the screen.

In such an instance, we can display a message to the user saying that JavaScript has been disabled for the website and that it is required for driving important functionalities.

But how do we know when JavaScript is disabled?

Well, that's what the <noscript> element is there for.

The <noscript> element represents content that is displayed when JavaScript is disabled by the browser.

The content inside <noscript> is rendered only when scripts are disabled; otherwise, it's hidden by the browser.

Consider the following code:

<h1>Working with scripts</h1>
<p>Trying to see the effect of the noscript element.</p>

<noscript>NOTE: Please enable JavaScript.</noscript>

We have an <h1>, followed by a <p>, followed by a <noscript>.

Live Example

If open up this document in the browser, we won't see the <noscript>'s content because JavaScript is enabled (by default) in the browser.

Let's try disabling it and then see the effect produced thereafter.

In you're on Google Chrome, click on the small lock icon (or the small information icon) before the URL in the address bar at the top of the window, as follows:

Lock icon in the address bar in Google Chrome.
Lock icon in the address bar in Google Chrome.

This opens up a small box containing information of the site:

Site information box in Google Chrome
Site information box in Google Chrome

Select Site Settings which will take you to another window for configuring the settings of the underlying site:

Site settings page in Google Chrome
Site settings page in Google Chrome

Scroll down this page until you see the option of JavaScript under the Permissions collection. (Currently, the option is right after the Notifications option).

JavaScript permission in site settings in Google Chrome.
JavaScript permission in site settings in Google Chrome.

Select the value Block from the dropdown at the right-hand side in order to disable JavaScript for the entire site.

Once we're done with this demonstration, you'll have to reset this option back to its default so that you can easily view our website with JavaScript enabled.

Once the permission has been changed, we'll get a reload notification on our original HTML document (the one with the <noscript> element) as follows:

Reload notification on Google Chrome
Reload notification on Google Chrome.

This notification is so that we can refresh the webpage in order to put the permission change into effect. Click on the Reload button and wait for the real action to happen.

As the webpage reloads, we see the text of the <noscript> element shown to us.

<noscript> displayed with JavaScript disabled in Google Chrome.
<noscript> displayed with JavaScript disabled in Google Chrome.


As noted before, since the example has been completed now, go on and reset the permission of JavaScript to Allow (Default) so that your experience of our website is not void of many useful functionalities powered by JavaScript.

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage