DEV Community

Cover image for AltSchool Of Engineering Tinyuka’24 Month 5 Week 4
Ikoh Sylva
Ikoh Sylva

Posted on

AltSchool Of Engineering Tinyuka’24 Month 5 Week 4

Please check out the revision of our previous class here. This week, we explored the Introduction to Focus and Blur, along with other exciting topics! Join me as we dive into these fascinating concepts together!

Image of a coded screen

Introduction to Focus and Blur

In web development, managing focus and blur events is essential for enhancing user interaction with forms and input elements. These events help control user input and provide visual feedback, which is crucial for creating a seamless experience.

Preparing for User Input

The focus event occurs when an input field or button receives user attention, typically through a click or keyboard navigation (like pressing the Tab key). This indicates that the user is ready to enter data.

An example of using the autofocus attribute in HTML can be seen below:

<input type="text" id="name" autofocus>

In this case, the input field will automatically receive focus when the page loads, allowing the user to start typing immediately.

When Input is Completed

The blur event occurs when a user moves away from an input field, indicating that they have finished interacting with it. This event is particularly useful for validating user input. For example, you can validate an email field when it loses focus:

const emailInput = document.querySelector('#email'); emailInput.addEventListener('blur', () => { if (!emailInput.value.includes('@')) { alert('Please enter a valid email address.'); } }); 
Enter fullscreen mode Exit fullscreen mode

Focus and Blur Methods

JavaScript provides the focus() and blur() methods to programmatically manage focus on elements. For instance, you can keep focus on an input field until valid input is entered:

const inputField = document.querySelector('#input'); inputField.addEventListener('blur', () => { if (inputField.value === '') { inputField.focus(); // Keep focus if the input is empty } }); 
Enter fullscreen mode Exit fullscreen mode

Handling JavaScript-Initiated Focus Loss

Focus loss can also occur due to JavaScript actions, such as displaying an alert or removing an element from the DOM. Developers should be cautious to avoid unintentionally causing focus loss, which might lead to unexpected behavior.

Using the Tab Index Attribute

By default, not all elements can receive focus. The tabindex attribute allows you to control focusability:

  • tabindex="1": Makes the element the first focusable item in the tab order.

  • tabindex="0": Follows the natural tab order and is focusable.

  • tabindex="-1": Not focusable via keyboard but can be focused programmatically.

Focus Delegation with Focusin and Focusout

Unlike focus and blur events, which do not bubble, focusin and focusout events do bubble up the DOM. This allows for easier management of focus events on parent elements, such as forms:

const form = document.querySelector('form'); form.addEventListener('focusin', (event) => { console.log('A child element received focus:', event.target); }); 
Enter fullscreen mode Exit fullscreen mode

Understanding Input Events

JavaScript provides several events that help manage user interactions with input elements, such as text fields and selection controls. Key events include change, input, cut, copy, and paste, each serving specific purposes in handling user input and clipboard operations.

Change Event

The change event is triggered when a user modifies the value of an input element and then moves the focus away from it. This event is particularly useful for form elements like text inputs, checkboxes, radio buttons, and select menus.

  • For text inputs, it occurs after the user finishes editing.

  • For checkboxes and select menus, it triggers immediately upon selection.

Example:

const checkbox = document.querySelector('#subscribe'); checkbox.addEventListener('change', () => { console.log('Checkbox state changed to: ', checkbox.checked); }); 
Enter fullscreen mode Exit fullscreen mode

Input Event

The input event fires instantly whenever the value of an input element changes, making it ideal for situations requiring real-time feedback. This includes typing, pasting, or even using speech recognition.

Example:

const passwordInput = document.querySelector('#password'); passwordInput.addEventListener('input', () => { const strength = passwordInput.value.length >= 8 ? 'Strong' : 'Weak'; console.log(`Password strength: ${strength}`); }); 
Enter fullscreen mode Exit fullscreen mode

Cut, Copy, and Paste Events

These events handle clipboard operations and are part of the ClipboardEvent class:

  • cut: Triggered when data is cut from an element.

  • copy: Triggered when data is copied to the clipboard.

  • paste: Triggered when data is pasted into an element.
    The event.clipboardData object allows access to the data being manipulated. You can prevent the default clipboard actions using event.preventDefault().

Example of handling the paste event:

const textArea = document.querySelector('textarea'); textArea.addEventListener('paste', (event) => { const pastedText = event.clipboardData.getData('text'); console.log('Pasted text: ', pastedText); event.preventDefault(); // Prevents the default paste action }); 
Enter fullscreen mode Exit fullscreen mode

Important Note

Clipboard data can only be accessed during user-initiated events (like cut, copy, and paste). Additionally, most browsers do not allow the dispatching of custom clipboard events with dispatchEvent, with Firefox being an exception.

Image of a cumputer lab

Overview of Form Submission

Form submission is a key feature in web applications, enabling users to input data and send it to a server for processing. In JavaScript, there are two primary methods to handle form submissions: the submit event and the form.submit() method.

The Submit Event

The submit event is triggered when a form is submitted. This event is crucial for validating form data before sending it to the server or for preventing the default submission behavior to handle it with JavaScript.

Forms can be submitted through two main actions:

  • Clicking a submit button.

  • Pressing the Enter key while focused on any input field within the form.

Example of handling the submit event:

const form = document.querySelector('form'); form.addEventListener('submit', (event) => { event.preventDefault(); // Prevents the default submission console.log('Form data submitted:', new FormData(form)); // Additional validation or processing logic can be added here }); 
Enter fullscreen mode Exit fullscreen mode

HTML Validation Attributes

HTML5 introduced several built-in validation attributes that simplify form validation without requiring JavaScript. These attributes include:

  • required: Ensures that the input field must be filled out.

  • minlength and maxlength: Specify the minimum and maximum length of text input.

  • min and max: Define the minimum and maximum values for numerical inputs.

  • pattern: Enforces a regular expression that the input's value must match.

  • type: Determines the type of input, such as email, url, or number, which triggers built-in validation mechanisms.

Example of using validation attributes in HTML:

<form> <input type="text" required minlength="3" maxlength="20" placeholder="Username"> <input type="number" min="1" max="100" required> <button type="submit">Submit</button> </form> 
Enter fullscreen mode Exit fullscreen mode

Introduction to the Constraint Validation API

The Constraint Validation API is a powerful tool in JavaScript that enables developers to manage the validity of form controls, customize error messages, and streamline the validation process. This API enhances user experience by providing immediate feedback on input validity.

Key Methods and Properties

1. checkValidity()
This method checks if the form control's value meets all validation constraints. It returns true if there are no validity issues.

Example:

const inputField = document.querySelector('#username'); if (!inputField.checkValidity()) { console.log('Input is invalid.'); } 
Enter fullscreen mode Exit fullscreen mode

2. setCustomValidity(message)
This method allows developers to set a custom error message for an input element, marking it as invalid. If a custom message is set, it will override the default validation message.

Example:

inputField.setCustomValidity('Username must be at least 3 characters long.'); 
Enter fullscreen mode Exit fullscreen mode

3. validationMessage
This property retrieves the validation message for an invalid element. It can be used to display specific error messages to users.

Example:

if (!inputField.checkValidity()) { alert(inputField.validationMessage); // Shows the custom error message } 
Enter fullscreen mode Exit fullscreen mode

4. validity
The validity property returns a ValidityState object that contains various properties indicating the specific validity issues. This includes:

  • valueMissing: True if the input is required but empty.

  • typeMismatch: True if the input type does not match the expected type (e.g., an email format).

  • patternMismatch: True if the input does not match the specified pattern.

Example:

if (inputField.validity.valueMissing) { console.log('Value is required.'); } 
Enter fullscreen mode Exit fullscreen mode

Image of a shield

I’m Ikoh Sylva, a passionate cloud computing enthusiast with hands-on experience in AWS. I’m documenting my cloud journey from a beginner’s perspective, aiming to inspire others along the way.

If you find my content helpful, please like and follow my posts, and consider sharing this article with anyone starting their own cloud journey.

Let’s connect on social media. I’d love to engage and exchange ideas with you!

LinkedIn Facebook X

Top comments (0)