Javascript Event Type Focus Essay

An event is a signal that something has happened. All DOM nodes generate such signals (but events are not limited to DOM).

Here’s a list of the most useful DOM events, just to take a look at:

Mouse events:

  • – when the mouse clicks on an element (touchscreen devices generate it on a tap).
  • – when the mouse right-clicks on an element.
  • / – when the mouse cursor comes over / leaves an element.
  • / – when the mouse button is pressed / released over an element.
  • – when the mouse is moved.

Form element events:

  • – when the visitor submits a .
  • – when the visitor focuses on an element, e.g. on an .

Keyboard events:

  • and – when the visitor presses and then releases the button.

Document events

  • – when the HTML is loaded and processed, DOM is fully built.

CSS events:

  • – when a CSS-animation finishes.

There are many other events. We’ll get into more details of particular events in next chapters.

Event handlers

To react on events we can assign a handler – a function that runs in case of an event.

Handlers is a way to run JavaScript code in case of user actions.

There are several ways to assign a handler. Let’s see them, starting from the simplest one.

HTML-attribute

A handler can be set in HTML with an attribute named .

For instance, to assign a handler for an , we can use , like here:

On mouse click, the code inside runs.

Please note that inside we use single quotes, because the attribute itself is in double quotes. If we forget that the code is inside the attribute and use double quotes inside, like this: , then it won’t work right.

An HTML-attribute is not a convenient place to write a lot of code, so we’d better create a JavaScript function and call it there.

Here a click runs the function :

As we know, HTML attribute names are not case-sensitive, so works as well as and … But usually attributes are lowercased: .

DOM property

We can assign a handler using a DOM property .

For instance, :

If the handler is assigned using an HTML-attribute then the browser reads it, creates a new function from the attribute content and writes it to the DOM property.

So this way is actually the same as the previous one.

The handler is always in the DOM property: the HTML-attribute is just one of the ways to initialize it.

These two code pieces work the same:

  1. Only HTML:

  2. HTML + JS:

As there’s only one property, we can’t assign more than one event handler.

In the example below adding a handler with JavaScript overwrites the existing handler:

By the way, we can assign an existing function as a handler directly:

To remove a handler – assign .

Accessing the element: this

The value of inside a handler is the element. The one which has the handler on it.

In the code below shows its contents using :

Possible mistakes

If you’re starting to work with event – please note some subtleties.

The function should be assigned as , not .

If we add brackets, then – will be the result of the function execution, so in the last code becomes (the function returns nothing). That won’t work.

…But in the markup we do need the brackets:

The difference is easy to explain. When the browser reads the attribute, it creates a handler function with the body from its content.

So the last example is the same as:

Use functions, not strings.

The assignment would work too. It works for compatibility reasons, but strongly not recommended.

Don’t use for handlers.

Such a call won’t work:

DOM-property case matters.

Assign a handler to , not , because DOM properties are case-sensitive.

addEventListener

The fundamental problem of the aforementioned ways to assign handlers – we can’t assign multiple handlers to one event.

For instance, one part of our code wants to highlight a button on click, and another one wants to show a message.

We’d like to assign two event handlers for that. But a new DOM property will overwrite the existing one:

Web-standard developers understood that long ago and suggested an alternative way of managing handlers using special methods and . They are free of such a problem.

The syntax to add a handler:

Event name, e.g. .
The handler function.
An optional argument, the “phase” for the handler to work. To be covered later. Usually we don’t use it.

To remove the handler, use :

Removal requires the same function

To remove a handler we should pass exactly the same function as was assigned.

That doesn’t work:

The handler won’t be removed, because gets another function – with the same code, but that doesn’t matter.

Here’s the right way:

Please note – if we don’t store the function in a variable, then we can’t remove it. There’s no way to “read back” handlers assigned by .

Multiple calls to allow to add multiple handlers, like this:

As we can see in the example above, we can set handlers both using a DOM-property and . But generally we use only one of these ways.

For some events handlers only work with

There exist events that can’t be assigned via a DOM-property. Must use .

For instance, the event (CSS animation finished) is like that.

Try the code below. In most browsers only the second handler works, not the first one.

Event object

To properly handle an event we’d want to know more about what’s happened. Not just a “click” or a “keypress”, but what were the pointer coordinates? Which key was pressed? And so on.

When an event happens, the browser creates an event object, puts details into it and passes it as an argument to the handler.

Here’s an example of getting mouse coordinates from the event object:

Some properties of object:

Event type, here it’s .
Element that handled the event. That’s exactly the same as , unless you bind to something else, and then becomes useful.
Window-relative coordinates of the cursor, for mouse events.

There are more properties. They depend on the event type, so we’ll study them later when come to different events in details.

The event object is also accessible from HTML

If we assign a handler in HTML, we can also use the object, like this:

That’s possible because when the browser reads the attribute, it creates a handler like this: . That is: its first argument is called , and the body is taken from the attribute.

Object handlers: handleEvent

We can assign an object as an event handler using . When an event occurs, its method is called with it.

For instance:

In other words, when receives an object as the handler, it calls in case of an event.

We could also use a class for that:

Here the same object handles both events. Please note that we need to explicitly setup the events to listen using . The object only gets and here, not any other types of events.

The method does not have to do all the job by itself. It can call other event-specific methods instead, like this:

Now event handlers are clearly separated, that may be easier to support.

Summary

There are 3 ways to assign event handlers:

  1. HTML attribute: .
  2. DOM property: .
  3. Methods: to add, to remove.

HTML attributes are used sparingly, because JavaScript in the middle of an HTML tag looks a little bit odd and alien. Also can’t write lots of code in there.

DOM properties are ok to use, but we can’t assign more than one handler of the particular event. In many cases that limitation is not pressing.

The last way is the most flexible, but it is also the longest to write. There are few events that only work with it, for instance and (to be covered). Also supports objects as event handlers. In that case the method is called in case of the event.

No matter how you assign the handler – it gets an event object as the first argument. That object contains the details about what’s happened.

We’ll learn more about events in general and about different types of events in the next chapters.

onblur Event

❮ Event Object

Example

Execute a JavaScript when a user leaves an input field:

<input type="text" onblur="myFunction()">

Try it Yourself »

More "Try it Yourself" examples below.


Definition and Usage

The onblur event occurs when an object loses focus.

The onblur event is most often used with form validation code (e.g. when the user leaves a form field).

Tip: The onblur event is the opposite of the onfocus event.

Tip: The onblur event is similar to the onfocusout event. The main difference is that the onblur event does not bubble. Therefore, if you want to find out whether an element or its child loses focus, you could use the onfocusout event. However, you can achieve this by using the optional useCapture parameter of the addEventListener() method for the onblur event.


Browser Support

Event
onblurYesYesYesYesYes


Syntax

In JavaScript, using the addEventListener() method:

object.addEventListener("blur", myScript);

Try it Yourself »

Note: The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.


Technical Details

Bubbles:No
Cancelable:No
Event type:FocusEvent
Supported HTML tags:ALL HTML elements, EXCEPT: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title>
DOM Version:Level 2 Events

More Examples

Example

Using "onblur" together with the "onfocus" event:

<input type="text" onfocus="focusFunction()" onblur="blurFunction()">

Try it Yourself »

Example

Event delegation: setting the useCapture parameter of addEventListener() to true:

<form id="myForm">
  <input type="text" id="myInput">
</form>

<script>
var x = document.getElementById("myForm");
x.addEventListener("focus", myFocusFunction, true);
x.addEventListener("blur", myBlurFunction, true);

function myFocusFunction() {
    document.getElementById("myInput").style.backgroundColor = "yellow";
}

function myBlurFunction() {
    document.getElementById("myInput").style.backgroundColor = "";
}
</script>

Try it Yourself »

Example

Event delegation: using the focusin event (not supported by Firefox):

<form id="myForm">
  <input type="text" id="myInput">
</form>

<script>
var x = document.getElementById("myForm");
x.addEventListener("focusin", myFocusFunction);
x.addEventListener("focusout", myBlurFunction);

function myFocusFunction() {
    document.getElementById("myInput").style.backgroundColor = "yellow";
}

function myBlurFunction() {
    document.getElementById("myInput").style.backgroundColor = "";
}
</script>

Try it Yourself »

❮ Event Object

0 Replies to “Javascript Event Type Focus Essay”

Lascia un Commento

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *