Event Handlers in JavaScript – an Introduction

Event Handlers in JavaScript – an Introduction

Event Handlers in Javascript - Free TutorialNow that we have covered what JavaScript is, let’s get down and do some by looking at Event Handlers!

An Event Handler is something that handles what happens when a user does something on your web page. If that sounds vague, it’s because it’s meant to be vague!

Users can do all sorts on your website – the question is what do you want to “listen” for?

Inline JavaScript and Event Handlers

One of the simplest ways of triggering something is to use inline JavaScript. That means using JavaScript inside HTML Tags.

<input type="button" value="Click Me" onClick="someFunction();">

To use inline JavaScript, we need to learn a new principle – that of Event Handlers.

What Is An Event?

In order to explain what an event handler actually is, it’s important to first understand what an event is – i.e. what are we ‘handling’?

An event is basically an action which either the browser or the user takes which interacts with the page. To keep things simple for this lesson, we will focus on actions the user of the page. These kind of actions include things like:

  • Clicking a button or link
  • Right clicking or double-clicking
  • Using tab to get the cursor into a text box
  • Typing inside a text box
  • Selecting a different form element from another
  • Scrolling up or down the page
  • Submitting a form

Let’s look at some of these in more detail!

Clicking on a Button

Clicking (the left mouse button) or pressing a button if you’re on a touch-screen device is detected by the onClick event handler. Don’t get confused with mobile phones or tablets – they still respond to onClick even though there’s nothing to click!

So let’s play with a button (flick to the ‘Result’ tab to use the button):


Everything you want to happen needs to be placed between the speech marks. What we have done here is trigger a JavaScript function called alert();. What the alert does is show a text-only box which sports one button called ‘OK’. This might be done to inform a user of something – say a required form field wasn’t filled in.

alert(); takes a string (a collection of characters wrapped in '') and then shows the box. Click the button to see!

You can include onclick on a variety of HTML tags, but bear in mind if you do this on a link that as soon as your action (whatever it is) has been carried out, the URL in your link tag will trigger.

Interacting With Text Boxes

There are a variety of actions available when dealing with text boxes, but for simplicity I want to cover the two main ones – when the text box is brought into focus (either by using a mouse/touch screen) or by using the tab key and when something else takes away that focus:

  • onFocus – when the cursor is active inside the text box
  • onBlur – when the cursor no longer is active.

Changing the Border and Background Color

One useful thing you can do in HTML Forms is highlight to the user which field they are currently changing. A useful method would be to change the elements border and background colours.

The first thing to bear in mind is that it is useful to set a default value in your CSS first:


Now we need to use JavaScript to modify those values. When changing something which is predefined in CSS, we access it using the .style attribute of the object in question.

CSS properties frequently employ hyphens to split out words – e.g. background-color. You cannot do this with JavaScript, as the hyphen will be seen as the mathematical ‘minus’ sign, causing your scripts to fail. Instead most css properties can be accessed by removing the hypen and capitalising every word (after the first word).
To demonstrate: background-color in JavaScript is .style.backgroundColor

So first we are going to use the onFocus event handler. I’ll give you the code and then explain it:


So we start doing stuff when the text box comes into focus. To access the properties of the object where onFocus is used, we can access it using this. JavaScript works in a hierarchy that works something like this:

object -> category of properties -> properties

Some are more levels in and some may be just one level in. So for the textbox’s border property, we take this route

this -> style -> border

But instead of the arrows we use full stops/periods: this.style.border='';

We can then use a CSS-esque value of 1px solid #c00. The same kind of hierarchy applies for the background colour: this.style.backgroundColor='#ee3';. Notice that both lines of code are situated between speech marks and are separated by semicolons. Each command in JavaScript should end in a semi-colon. The end result is this:


(Due to the way CodePen functions you may need to click away from your text box to see the new border color).

The problem with only doing this one way is that when the text box no longer has the focus it still retains the style. How do we get round this? By using onBlur to reset the values back to what we have with the original CSS!


The Astute among you will know that this effect can be done within CSS’s :focus definition. But this is an example of what can be achieved with JavaScript.

Setting a Default Value

Another use inside text boxes might be to set a default value but then clear that onFocus. Although HTML5 has a placeholder attribute, older browsers don’t support it and some newer browsers struggle to display it well. So we will just set up a normal text box and then modify it:


This time we have directly accessed the text box’s value (what text is in it) via this.value='';. You could use this.value to change the text completely if you wanted to. (Note: try using this.value on a button’s onClick event to change the button text!).

By giving the text box an empty string we are just saying ‘the text box should have nothing in it’. Normal CSS currently cannot access or modify a form field’s value so this is one extra feature you can give your form fields!

Submitting a Form

One thing you might want to do is thank a website visitor for filling in one of your forms. Rather than just redirecting them to a whole web page with just a single ‘thank you for your submission’ line on it, why not give them an alert() text box instead?

Really easy to achieve via the onSubmit Event Handler.

<form action="/path/to/email/script.php" method="post" onSubmit="alert('Thank you so much for your time!');">

This form then waits until a submit button is pressed (e.g. <input type="submit">) – then our alert() alert is triggered. Finally our form will be processed by a PHP script designed to send emails.

Detecting When a Form Field Has Changed

Various form elements don’t have text inputs:

  • Drop-down select boxes
  • Radio and Checkbox Inputs
  • Multi-select options

If you want to know when the value of a form field has changed, then you can use the onChange Event Handler. For the final example of this quick introduction to JavaScript events, we are going to

  1. Create a drop-down box to select a planet
  2. Output the planet selected to another text box
  3. Thank the user for selecting the planet they have when they want to finish.

Firstly – Naming Conventions

So far we have only accessed the current item’s values. We have done that through the this object. However, that is only appropriate when dealing with the current object. If we want to talk to other items on the page we need to look at how to reference those objects.

Method 1 – Using IDs
If we give a HTML element a unique ID – <input type="text" id="firstName"> then we can access it by using JavaScript’s getElementById() function, which works as follows:


Note: IDs are case-sensitive so watch your upper and lower cases!

Method 2 – Using Names
All form items should have a NAME property already. This is often how CMS’ and email scripts pull the values out of the form. To access an item using its name, however, you have to get into the form itself first. To make this easy, go ahead and give your form a name: <form action="/path/to/email/scripts.php" method="post" name="myForm">.

Again this is case sensitive.

Now to access our ‘firstName’ field, make sure that you have name="firstName" in your text box. Great! Now you have given a NAME to both your form and the textbox we can access it with JavaScript:


JavaScript arrays is for a future lesson. But for now understand that the use of square brackets means that item is an array – which means there is possibly more than one of that kind of object on the page. In our case, forms[] is an array because there may be more than one form on the page – e.g.:

  • A Login Form
  • A Newsletter Signup Form
  • A Contact Form
  • A Poll Form

And so on and so forth. By specifying forms['myForm'] we want to access only the form with the name myForm.

elements[] is also an array because most forms have more than one field to them. So we have said that we want to access only the element called firstName only in the form called myForm.

This is a long way to do it, but it again demonstrates the importance of object hierarchy which we will be coming back to time and again.

Example Script

Right let’s build our planetary form! For simplicity I’m going to use Method 1 – the ID method. Here’s the full code snippet and then I’ll walk you through it!


  • To make things simple – our three form elements – the drop-down box, the text box and the button have an ID assigned to them. The select box has id="planets", the text box has id="planetChosen" and the button has id="submitButton".
  • To protect the textbox from manual tampering, we have used the onFocus() event handler. What happens if you try to click in the box is that we harness the blur() function which ‘unfocuses’ it.
  • The button has an onClick() event handler but is initially disabled via HTML’s disabled="disabled" property. Once the button is enabled (which we will come to) this line is triggered: onClick="alert('Thank you for selecting '+document.getElementById('planetChosen').value);. This generates a single alert box which says “Thank you for selecting ” – and then whatever the text in the textbox (id: planetChosen) is.

The more complicated snippet is how we handle the drop-down box. A <select> box can be triggered onChange(). That means if you click it but don’t change the option selected, then nothing happens. Note that this is determined on whether <option value="value"> changes, not the display text.

So, once the value changes, we want to put that value into the text box. So we target the textbox’s value property: document.getElementById('planetChosen').value=. But how do we determine the value selected? Unlike a textbox, you can’t just grab a select box’s “value”. That’s because it’s made up of multiple different options. In coding terms this is an ‘array list’ – we will come to arrays in another lesson. All you need to think about is that we need to grab the number of the item in the list and then pull out the text value you set in the <option> tag.

document.getElementById('planetChosen').value = this.options[this.selectedIndex].value;

So this.options[] grabs the list of all your <option> tags. this.selectedIndex grabs the number of the item currently selected. And only then can it grab the value item.

The last thing we have done here is to re-enable the button, which conversely is achieved by setting no value to the disabled property. document.getElementById('submitButton').disabled='';.

So in this example code you have used the following Event Handlers:

  • onChange
  • onFocus
  • onClick

Triggering Functions

I will go into more detail about functions in a future lesson, but this give us a quick opportunity to see how event handlers can be used to trigger functions. Here’s an example code snippet:


Our function here does nothing on its own. The reason is that it needs something to trigger it – an event of some description. If you wanted to you could use the BODY tag’s onLoad Event Handler to wait for the page to load and then trigger our function – which just displays a simple alert() message. But we can equally call a function using another event handler, like onClick for a button. So you can call the same function in a variety of different ways.

Summary of Other Event Handlers

There are a lot of event handlers but here are some for your reference:

  • onMouseOver: the same as CSS’s :hover this triggers code when the cursor is over an element. Do be careful using this one in the era of touchscreens, as we currently have no way of detecting if a finger is over, but not pressing, something on our page!
  • onMouseOut: this triggers when a cursor is no longer over an element. The same touchscreen warning applies.
  • onMouseDown, onMouseUp: detects whether a mouse button is in the down position (onMouseDown) or has moved to the up position (onMouseUp).
  • onDblClick: detect if the left mouse button has double-clicked, or a finger has double-pressed in quick succession.
  • onKeyDown, onKeyUp: detect if a keyboard key is either being pressed (onKeyDown) or if a keyboard button has been released (onKeyUp).
  • onKeyPress: detects if a keyboard button has been pressed (i.e. both KeyDown and KeyUp have triggered).
  • onResize: applies to the body or a window. This is used to determine if the size of the viewable area (in the case of the BODY tag) or the window has changed.
  • onUnload: triggers a function if the site is about to be unloaded – i.e. the page changes, or the browser window/tab is about to be closed.
  • onScroll: can be triggered when the whole page, or a scrollable element (i.e. a textarea or a scrollable element) is scrolled up or down. Can be used to keep something on the screen regardless of how far the user has scrolled.
  • onSubmit: Used for forms, run some code once the form has been submitted. Very useful for error checking in forms.

TL;DR JavaScript Event Handlers

With JavaScript, you can detect a wide variety of user interactions with your page. This enables you to run your code based on the user’s behaviour. This allows us to create a new layer of interactivity between the user and your site, or web application. Take time to experiment with some of these new event handlers. Use the example code to create your own events!

<< What is JavaScript?

Recent JavaScript Tutorials

[lptw_recentposts layout=”grid-medium” post_type=”page” link_target=”self” fluid_images=”true” height=”300″ featured_height=”300″ min_height=”0″ space_hor=”10″ space_ver=”10″ columns=”3″ order=”DESC” orderby=”date” posts_per_page=”6″ post_offset=”0″ reverse_post_order=”false” exclude_current_post=”true” color_scheme=”dark” override_colors=”true” background_color=”#212121″ text_color=”#ffffff” excerpt_show=”true” excerpt_lenght=”25″ ignore_more_tag=”false” read_more_show=”true” read_more_inline=”true” read_more_content=”Read more →” show_date_before_title=”false” show_date=”true” show_time=”true” show_time_before=”false” show_subtitle=”false” date_format=”F j, Y” time_format=”g:i a” no_thumbnails=”hide”]

Spread the Word

Share This On FacebookShare This On TwitterShare This On LinkedinShare This On Google PlusShare This On PinterestShare This On Mail