Focus and Blur Events

Focus And Blur Events

Focus and blur events in JavaScript are essential for creating interactive, user-friendly interfaces. These events allow developers to handle what happens when an element gains or loses focus, such as input fields, buttons, or other interactive UI components. By leveraging these events, you can enhance user accessibility and create intuitive behaviors in your applications.

In this section, we’ll cover the following topics:

  • What Are Focus and Blur Events?
  • Implementing Focus and Blur Events with AI Assistance
  • Best Practices for Focus and Blur Events

What Are Focus and Blur Events?

Focus and blur events let developers respond to changes in user interaction with specific elements on a webpage. When an element is "focused," it becomes active and ready for input. On the other hand, when it "blurs," the focus shifts away, triggering a different set of actions.

Common Focus and Blur Events

  • focus: Triggered when an element gains focus.
  • blur: Triggered when an element loses focus.
  • focusin: Similar to focus, but it bubbles up the DOM tree.
  • focusout: Similar to blur, but it bubbles up the DOM tree.

Implementing Focus and Blur Events with AI Assistance

Focus and blur events can be implemented using AI-powered workflows to create engaging, dynamic, and accessible web applications. This guide covers practical examples to demonstrate how to integrate these events effectively.

Preparing for Practice Files
This course takes a hands-on approach, allowing you to apply the techniques covered in real-world scenarios. We'll be using a structured folder layout. Before proceeding with the examples, please ensure the following files are prepared:

/your-project-folder/  
  |─07-07-focus-and-blur-events/ (<- sub-folder)  
    |─ example-1.css  
    |─ example-1.html  
    |─ example-1.js  
    |─ example-2.css  
    |─ example-2.html  
    |─ example-2.js
    |─ example-3.css  
    |─ example-3.html  
    |─ example-3.js
    |─ example-4.css  
    |─ example-4.html  
    |─ example-4.js

For your convenience, these files are also available on our GitHub repository.

AI Case 1: Highlighting Buttons for Accessibility

Highlighting buttons using focus and blur events enhances accessibility by providing visual feedback to users.

Sample AI prompt:

Create a button that highlights when focused and reverts when it loses focus.

Include:

  • HTML (example-1.html): Structure a single button with an instruction for the user to focus on it (via click or tab key) to see the highlight effect.
  • CSS (example-1.css): Style the button with a smooth box-shadow and scaling effect when focused. Ensure the transition is fluid.
  • JavaScript (example-1.js):: Remove the highlight effect when the button loses focus. Add comments for clarity.

Sample code output:

07-07-focus-and-blur-events/example-1.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Highlight Button on Focus</title>
    <link rel="stylesheet" href="example-1.css" />
  </head>
  <body>
    <div class="container">
      <h1>Highlight Button on Focus</h1>
      <p>
        Focus on the button below (by clicking or tabbing) to see the highlight
        effect. The highlight will disappear when the button loses focus.
      </p>
      <button id="highlight-button">Click Me</button>
    </div>
    <script src="example-1.js"></script>
  </body>
</html>

07-07-focus-and-blur-events/example-1.css
body {
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  height: 100vh;
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
}

.container {
  text-align: center;
  margin-top: 20px;
}

#highlight-button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  transition: box-shadow 0.3s ease, transform 0.2s ease;
}

#highlight-button:focus {
  box-shadow: 0 0 15px rgba(0, 123, 255, 0.7);
  transform: scale(1.05);
}

07-07-focus-and-blur-events/example-1.js
document.getElementById("highlight-button").addEventListener("blur", () => {
  document.getElementById("highlight-button").style.boxShadow = "";
});

Instructions to see the results:
Save the code above in each file. Open the HTML file in your browser to view how the button is highlighted on focus.

To see how the code works, you can also check out the link below.

Demo Web Page 11

AI Case 2: Tooltip on Focus

Tooltips provide users with helpful hints about an element.

Sample AI prompt:

Create a button with a tooltip that appears above it when focused.

Include:

  • HTML (example-2.html): Structure a button with an associated tooltip. Include an instruction for the user to focus on the button to see the tooltip.
  • CSS (example-2.css): Style the tooltip so it appears above the button without overlapping. Use a smooth transition for visibility.
  • JavaScript (example-2.js): Show the tooltip on button focus and hide it when the button loses focus. Add comments for clarity.

Sample code output:

07-07-focus-and-blur-events/example-2.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Tooltip on Focus</title>
    <link rel="stylesheet" href="example-2.css" />
  </head>
  <body>
    <div class="container">
      <h1>Tooltip on Focus</h1>
      <p>
        Focus on the button below (by clicking or tabbing) to see a tooltip
        appear. The tooltip will disappear when the button loses focus.
      </p>
      <div class="tooltip-container">
        <button id="tooltip-button">Click me</button>
        <div id="tooltip">This is a tooltip</div>
      </div>
    </div>
    <script src="example-2.js"></script>
  </body>
</html>

07-07-focus-and-blur-events/example-2.css
body {
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  height: 100vh;
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
}

.container {
  text-align: center;
  margin-top: 20px;
}

.tooltip-container {
  position: relative;
  display: inline-block;
}

#tooltip {
  position: absolute;
  bottom: 110%; /* Place above the button */
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 14px;
  white-space: nowrap;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  display: none;
}

.tooltip-container:focus-within #tooltip {
  display: block;
}

#tooltip-button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.tooltip-container #tooltip-below {
  top: 110%; /* Place below the button */
  bottom: auto; /* Reset bottom value */
}

07-07-focus-and-blur-events/example-2.js
const button = document.getElementById("tooltip-button");
const tooltip = document.getElementById("tooltip");

button.addEventListener("focus", () => (tooltip.style.display = "block"));
button.addEventListener("blur", () => (tooltip.style.display = "none"));

Instructions to see the results:
Save the code above in each file. Open the HTML file in your browser to view the tooltip functionality.

To see how the code works, you can also check out the link below.

Demo Web Page 12

AI Case 3: Preventing Accidental Actions

This example prompts the user for confirmation before proceeding with an action.

Sample AI prompt:

Create a button that waits for 2 seconds on focus before prompting the user for confirmation.

Include:

  • HTML (example-3.html): Structure a single button with an instruction for the user to focus on it to trigger the confirmation prompt.
  • CSS (example-3.css): Style the button with transitions and bold text to make it visually appealing.
  • JavaScript (example-3.js): Use a timer to show a confirmation message after 2 seconds of focus. Cancel the timer if the button loses focus. Add comments for clarity.

Sample code output:

07-07-focus-and-blur-events/example-3.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Prevent Accidental Actions</title>
    <link rel="stylesheet" href="example-3.css" />
  </head>
  <body>
    <div class="container">
      <h1>Prevent Accidental Actions</h1>
      <p>
        Focus on the button below (by clicking or tabbing) and wait for 2
        seconds to see a confirmation prompt. If you move focus away, the prompt
        will not appear.
      </p>
      <button id="confirm-button">Submit</button>
    </div>
    <script src="example-3.js"></script>
  </body>
</html>

07-07-focus-and-blur-events/example-3.css
body {
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  height: 100vh;
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
}

.container {
  text-align: center;
  margin-top: 20px;
}

#confirm-button {
  padding: 12px 24px;
  font-size: 16px;
  font-weight: bold;
  background-color: #ffc107;
  color: #212529;
  border: 1px solid #ffc107;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease, transform 0.2s ease;
}

#confirm-button:focus {
  background-color: #e0a800;
  transform: scale(1.1);
}

07-07-focus-and-blur-events/example-3.js
const confirmButton = document.getElementById("confirm-button");

let timer;
confirmButton.addEventListener("focus", () => {
  timer = setTimeout(() => alert("Are you sure?"), 2000);
});
confirmButton.addEventListener("blur", () => clearTimeout(timer));

Instructions to see the results:
Save the code above in each file. Open the HTML file in your browser to view the confirmation prompt functionality.

To see how the code works, you can also check out the link below.

Demo Web Page 13

AI Case 4: Changing Button Appearance Dynamically

Dynamic button styles can improve visual engagement.

Sample AI prompt:

Create a button that changes its text and background color when focused and reverts to its original state when it loses focus.

Include:

  • HTML (example-4.html): Structure a single button with an instruction for the user to focus on it to observe the dynamic changes.
  • CSS (example-4.css): Style the button with smooth transitions for background color and text changes.
  • JavaScript (example-4.js): Change the button's text and background color on focus and reset them on blur. Add comments for clarity.

Sample code output:

07-07-focus-and-blur-events/example-4.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Dynamic Button Appearance</title>
    <link rel="stylesheet" href="example-4.css" />
  </head>
  <body>
    <div class="container">
      <h1>Dynamic Button Appearance</h1>
      <p>
        Focus on the button below (by clicking or tabbing) to change its text
        and background color. The button will revert to its original state when
        it loses focus.
      </p>
      <button id="dynamic-button">Button</button>
    </div>
    <script src="example-4.js"></script>
  </body>
</html>

07-07-focus-and-blur-events/example-4.css
body {
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  height: 100vh;
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
}

.container {
  text-align: center;
  margin-top: 20px;
}

#dynamic-button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s ease;
}

#dynamic-button:focus {
  background-color: #28a745;
  color: white;
  font-weight: bold;
  transform: scale(1.1);
}

#dynamic-button:active {
  transform: scale(1.05);
}

07-07-focus-and-blur-events/example-4.js
const button = document.getElementById("dynamic-button");
button.addEventListener("focus", () => {
  button.textContent = "Focused!";
  button.style.backgroundColor = "green";
});
button.addEventListener("blur", () => {
  button.textContent = "Button";
  button.style.backgroundColor = "";
});

Instructions to see the results:
Save the code above in each file. Open the HTML file in your browser to see dynamic button behavior.

To see how the code works, you can also check out the link below.

Demo Web Page 14

Best Practices for Focus and Blur Events

Focus and blur events are effective tools for enhancing user interactions. Follow these key practices for optimal results:

  • Prioritize Accessibility: Ensure all interactions triggered by focus and blur events work seamlessly with a keyboard or assistive technologies. For example, test the flow for users navigating with the Tab key.
  • Simplify Event Handlers: Avoid attaching complex or resource-intensive actions to focus events. Use them for lightweight tasks like showing a tooltip or highlighting an element.
  • Leverage CSS for Visual Effects: Use CSS for straightforward styling like focus outlines or hover effects, while reserving JavaScript for more dynamic behaviors.
  • Maintain Consistency: Ensure similar elements in your interface behave predictably to avoid confusing users, such as applying consistent tooltip behavior for buttons.

By focusing on these best practices, you can design user-friendly and accessible web interfaces that enhance the overall experience without overwhelming users.

Reference links:

Focus and Blur Events on MDN

FAQ: Focus and Blur Events in JavaScript

What are Focus and Blur Events?

Focus and blur events let developers respond to changes in user interaction with specific elements on a webpage. When an element is "focused," it becomes active and ready for input. On the other hand, when it "blurs," the focus shifts away, triggering a different set of actions.

What are the common Focus and Blur Events?

Common focus and blur events include:

  • focus: Triggered when an element gains focus.
  • blur: Triggered when an element loses focus.
  • focusin: Similar to focus, but it bubbles up the DOM tree.
  • focusout: Similar to blur, but it bubbles up the DOM tree.

How can AI assist in implementing Focus and Blur Events?

Focus and blur events can be implemented using AI-powered workflows to create engaging, dynamic, and accessible web applications. AI can help automate and optimize the integration of these events, making the development process more efficient.

What are some best practices for using Focus and Blur Events?

Best practices for focus and blur events include:

  • Prioritize Accessibility: Ensure all interactions work seamlessly with a keyboard or assistive technologies.
  • Simplify Event Handlers: Use focus events for lightweight tasks like showing a tooltip or highlighting an element.
  • Leverage CSS for Visual Effects: Use CSS for straightforward styling, reserving JavaScript for dynamic behaviors.
  • Maintain Consistency: Ensure similar elements behave predictably to avoid confusing users.

How can Focus and Blur Events enhance accessibility?

Focus and blur events enhance accessibility by providing visual feedback and ensuring that interactive elements are easily navigable using a keyboard or assistive technologies. For example, highlighting buttons on focus can help users with visual impairments.

JavaScript Coding with AI
Course Content