Skip to content

The Mysterious World of Forms: submit, change, focus, blur Events

Recently, there’s been a constant atmosphere of repairs at home. The other day, I tried to replace the kitchen faucet. I said, ‘This is very simple, I can handle it myself’. Of course, I was mistaken. The faucet socket was a bit rusty, and the switch tip slipped. The result? A half-hour job took half a day, and I hurt my hand in the process. Anyway, let this be my ‘technical fail’ story 🙂

Actually, that’s not the main topic, but you know, sometimes people start talking about memories when discussing topics, so I also did. While exploring form-related things, that memory came to my mind. When developing websites, sometimes things don’t go as expected. That’s why understanding events like ‘submit’, ‘change’, ‘focus’, and ‘blur’ is very important, in my opinion. Mastering these basic events can elevate the user experience to a whole new level.

Now, thinking about it, these events are present in every aspect of our lives. You go to the market and like a product, pick it up, and inspect it. That inspection process is kind of like ‘focus’. Then, when you say, ‘I’ll buy this!’ and go to the checkout, it becomes ‘submit’. When you get home and think, ‘Did I buy the right thing?’, it might create a slight ‘blur’ effect. By the way, these analogies are always bouncing around my mind. What can I do 🙂

In the web world, these events are triggered when a user interacts with a form. Imagine you’re visiting a website with a registration form. As you click into boxes and type something, many things happen in the background. To understand this ‘background stuff’ better, let’s analyze these events one by one.

Submit Event: The Last Word of the Form

The most well-known of form events is ‘submit’. This event triggers when a user clicks the ‘Submit’ button or presses Enter on the form. You can think of it as the final decision point of the form. The user has filled all the information, clicks ‘OK’ one last time, and submits. That moment is when the ‘submit’ event fires.

This event can be captured to prevent the form from submitting or to perform a final check before data is sent somewhere. For example, checking whether passwords match or if the email format is correct. In such cases, you can catch the ‘submit’ event and display warnings on the user’s screen, prompting corrections before sending the form. This really helps avoid unnecessary waiting or error messages.

In JavaScript, you can listen for this event using `addEventListener(‘submit’, function(event) { … })`. To prevent the default form submission, you call `event.preventDefault()`. This is one of my most-used tricks. Sometimes I forget to do this in my programs, and then I wonder, ‘Why is the program closing?’ Turns out, I forgot to prevent the submit event 🙂

Change Event: When Something Changes

Now, let’s move on to the ‘change’ event. This triggers when the value of an input element (like text, checkbox, select) changes. For example, when you write in a text box or select a different option from a dropdown, or check a checkbox, the ‘change’ event fires.

This event is great for providing real-time feedback. Suppose a user selects a country. Using the ‘change’ event, you can automatically update the city list based on the selected country. Or, if there’s an input that changes the product price, you can instantly update the total price. It’s a stylish way to say, ‘Hold on, we’re handling it’ and show immediate updates to the user.

I think the ‘change’ event makes user interaction more dynamic. Sometimes it triggers even when the user types and then deletes, which can be annoying, but overall it’s very useful. There are some nuances about when exactly it triggers, but the main idea is: if a value has changed, ‘change’ fires.

Focus and Blur Events: Where Are You and Where Are You Heading?

These two are like opposites. The ‘focus’ event fires when an element (usually an input field) becomes active – when the user clicks on it or navigates to it with the tab key. The ‘blur’ event is the opposite; it triggers when focus moves away from the element, such as clicking elsewhere or switching to another field with the tab key.

These events are very useful for giving hints to the user or for validation. For example, when an input gets focus, you might display a small clarification about what it’s for. Or, when the user leaves the field (blur), you can immediately check if the input is correct. Sometimes I forget to add focus or blur events and then wonder, ‘Why isn’t anything happening when I click the password field?’ It’s funny, isn’t it?

These events are essential for improving user experience. For example, in a form, you might highlight required fields in a specific color when focused, and if left empty upon blur, draw a red border. This provides visual guidance to the user. It’s like the suggestion pop-ups you see in Google search—working with ‘focus’ logic. Isn’t it beautiful?

Let’s think about these events together. You are filling out a form: you click an input (‘focus’ triggers), type something, maybe make a mistake, then move to another (‘blur’ triggers, and an error message may appear). Select an item from a list (‘change’ triggers). Finally, you click ‘Submit’ (‘submit’ triggers).

All these events make websites interactive. Using them correctly makes it easier for users to navigate and perform actions smoothly. For beginner developers like me, it can be a bit confusing at first, but with practice, it becomes natural.

Sample Code: How to Use These Events Step by Step

Let’s create a simple example where a username input field changes its border color when focused, shows an alert if left empty on blur, and displays a message when the form is submitted.

First, a problematic snippet that might not work as expected:

// WRONG INITIAL ATTEMPT (Debugging needed) const userNameInput = document.getElementById('username'); const form = document.getElementById('myForm');

userNameInput.addEventListener('focus', function() { userNameInput.style.borderColor = 'blue'; // When focused, turn blue });

// This part might be problematic, to show warning if empty, on blur: userNameInput.addEventListener('blur', function() { if (userNameInput.value === '') { userNameInput.style.borderColor = 'red'; // Turn red if empty } else { userNameInput.style.borderColor = ''; // Reset to default } });

form.addEventListener('submit', function(event) { if (userNameInput.value === '') { alert('Username cannot be empty!'); event.preventDefault(); // Prevent form submission } else { alert('Form is submitting!'); // Just an alert, actual submission code needed } });

This code has some issues. In the 'blur' event, if the user types and then deletes, the red border may stay. Also, the submit event always shows 'Form is submitting!' alert, and the form doesn't really submit because `preventDefault()` is always called. So, we need a more reliable approach.

Here's a better method with sound event management:

// CORRECT APPROACH (Better event handling) const userNameInput = document.getElementById('username'); const form = document.getElementById('myForm');

// Focus event: Change border to blue userNameInput.addEventListener('focus', function() { userNameInput.style.borderColor = 'blue'; });

// Blur event: Check value, set border color accordingly, and give validation message userNameInput.addEventListener('blur', function() { if (userNameInput.value.trim() === '') { // Remove spaces too userNameInput.style.borderColor = 'red'; userNameInput.setCustomValidity('Username cannot be empty!'); // Use browser's native validation prompt } else { userNameInput.style.borderColor = 'green'; // Valid input, turn green userNameInput.setCustomValidity(''); // Clear validation message } });

// Change event: optional, update border based on change, may overlap with blur but shown here userNameInput.addEventListener('change', function() { if (userNameInput.value.trim() === '') { userNameInput.style.borderColor = 'red'; } else { userNameInput.style.borderColor = 'green'; } });

// Submit event: Check value before submitting form form.addEventListener('submit', function(event) { if (userNameInput.value.trim() === '') { alert('Username cannot be empty!'); // Show user a warning event.preventDefault(); // Stop submission } else { alert('Form is being submitted!'); // For now, just alert, actual data submission occurs here // For example, using fetch API: // fetch('/api/user', { method: 'POST', body: JSON.stringify({ username: userNameInput.value }) }) // .then(response => response.json()) // .then(data => console.log('Success:', data)) // .catch((error) => console.error('Error:', error)); } });

Now, with this setup, we trim spaces and utilize the browser's native validation display with `setCustomValidity`. The 'change' event is for additional control, though it might overlap with 'blur'. In real applications, more comprehensive validation libraries can be used, such as searching on Google.

In summary, 'submit', 'change', 'focus', and 'blur' events are the cornerstones of form interaction in web development. Mastering them allows for creating user-friendly, effective web applications. I use these events heavily in my projects, which makes my work much easier. Sometimes I forget, but when I remember, I think, 'Glad I did that :)'

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.