How to Use onfocus with JavaScript

  • 4 min read
  • September 7, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

The HTML DOM event onfocus is triggered whenever an HTML element it is assigned to receives focus from the user.

This event is usually used with <input>, <select> and <a> tags. These are tags that are generally associated with user interaction.

There is a similar DOM eventonblur – which triggers when the element that it is assigned to loses focus.

The onfocus DOM event is very similar to the DOM event onfocusin. The primary difference between the two is that onfocusin bubbles events up to its parents, while onfocus does not.

Basic example

HTML

<input type="text" placeholder="Enter your password" onfocus="alertMsg()">

JavaScript

function alertMsg() {
 console.log('Always keep your password safe!')
}

In the above example, there is an <input> tag with a placeholder asking the user to enter a password. Inside the tag, lies the triggering DOM eventonfocus. When the element receives focus, it will execute the function alertMsg(). This function then prints the message ‘Always keep your password safe!’ to the console.

Note: You may be tempted to use the alert() function here. This is a potential anti-pattern; using alert with onfocus can be problematic. The reason this is problematic is due to the behavior of the browser. When an alert() window is shown, the focus changes twice – once to display the alert, then once again when the alert is dismissed. This can potentially create an infinite loop, with the user unable to stop receiving alert windows. We highly recommend you create a custom message modal for these types of situations, so that you can more tightly control the focus flow of the application.

What is Focus?

Focus is a term used to refer to the current HTML element that a user is working with. An HTML element gets focus when it is clicked, or when the user tabs into it. You can also achieve the same result by using the autofocus attribute.

How to use onfocusin / onfocusout

To better understand how to use onfocusin and onfocusout, we need to discuss the concept of bubbling. Bubbling takes place when an event for an element is also pushed to its parent elements – this is known as “bubbling up”. It is also possible for bubbling to apply to children, in which case the event is “bubbling down”.

Let’s explore this with an example. In the code below, we want to highlight the focused input based upon user activity. You could achieve this by placing an onfocus event to each input, but it is much easier to leverage the onfocusin event on the parent <form> element, as shown below:

HTML

<form onfocusin="markYellow(event)">
  <input type="text" placeholder="First name">
  <input type="text" placeholder="Last name">
</form>

JavaScript

function markYellow(event) {
  const currInput = event.target;
  currInput.classList.add('marked');
}

CSS

.marked {
  background-color: yellow;
}

In the example above we only defined onfocusin for the parent form, but every input receives the correct yellow highlight when focused. This is an example of the event bubbling down into the children elements of the <form>. The method uses the event parameter , which is passed to the triggered function, to determine the current input to modify.

Note: In the above example, the highlighting will not disappear when the field loses focus – this is because we’ve directly updated the element with a new class and its associated CSS. To remove the highlight, we’ll want to use onfocusout, described below.

Use onfocusout:

The onfocusout event is fired whenever a field loses focus, and bubbles in the same way as onfocusin. Using this keyword, we can update our code example above to turn off highlights when a field loses focus. We start by adding the onfocusout property to our parent <form> element:

HTML

<form onfocusin="markYellow(event)" onfocusout="demark(event)">

Now, when a field in the form loses focus, the DOM will invoke the function demark(), defined below:

JavaScript

function demark(event) {
 const currInput = event.target;
 currInput.classList.remove('marked');
}

This function is very similar to the one which added the yellow background. In fact, the only elements of the function that change are the function name and, most importantly, the use of remove() instead of add().

With this minor change, we now have a fully-functional form that will highlight the currently-focused field, removing the highlight when the field loses focus.

 

Related Articles:

JavaScript – How to Change CSS

JavaScript – How to Use setAttribute

JavaScript – How to Use the onclick DOM Event

Related Posts

How to Change CSS Using JavaScript

How to Change CSS Using JavaScript

Cascading Style Sheets (CSS) is used to design the layout of a webpage. CSS is a set of structured rules describing the layout of elements in

How to Use the for…in Statement in JavaScript

How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties. Basic for…in loop example The following code demonstrates a basic example using the for…in statement

How to use the for…of Statement in JavaScript

How to use the for…of Statement in JavaScript

The for…of statement was introduced in ECMAScript2015 (ES6) and adds a powerful new type of loop to JavaScript. JavaScript offers many different types of loops, each