Simple JavaScript example to highlight selected form fields with CSS for improved usability and accessibility in any HTML form.
// Complete code to highlight the currently selected form field
// HTML + CSS + JavaScript integrated in a single file for ease of use
const formHTML = `
<style>
/* Base style for input fields */
input {
padding: 8px;
margin: 6px 0;
border: 2px solid #ccc;
border-radius: 4px;
font-size: 16px;
transition: border-color 0.3s, box-shadow 0.3s;
width: 100%;
box-sizing: border-box;
}
/* Style applied to the active (focused) field */
input.evidenziato {
border-color: #007BFF; /* bright blue */
box-shadow: 0 0 8px rgba(0, 123, 255, 0.6);
outline: none; /* removes the browser's default border */
}
/* Form container for sizing and layout */
.form-container {
max-width: 400px;
margin: 20px auto;
font-family: Arial, sans-serif;
}
label {
display: block;
margin-top: 12px;
font-weight: bold;
}
button {
margin-top: 16px;
padding: 10px 15px;
font-size: 16px;
background-color: #007BFF;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #0056b3;
}
</style>
<div class="form-container">
<form id="mioForm">
<label for="nome">Name:</label>
<input type="text" id="nome" name="nome" placeholder="Enter your name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="example@domain.com" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="Enter your password" required>
<button type="submit">Submit</button>
</form>
</div>
`;
// Insert the form into the page body
document.body.innerHTML = formHTML;
// Function to handle highlighting of the active field
function evidenziaCampi() {
// Select all inputs inside the form
const inputs = document.querySelectorAll('#mioForm input');
// For each input add listeners for focus and blur
inputs.forEach(input => {
// When the field receives focus, add the 'evidenziato' class
input.addEventListener('focus', () => {
input.classList.add('evidenziato');
});
// When the field loses focus, remove the 'evidenziato' class
input.addEventListener('blur', () => {
input.classList.remove('evidenziato');
});
});
}
// Initialize the function after the page loads
window.addEventListener('DOMContentLoaded', evidenziaCampi);HTML: form structure with input fields (text, email, password)
CSS: definition of base style and highlighted style (focus)
JavaScript: handling of 'focus' and 'blur' events to add/remove CSS classes
Software configuration: no external dependencies, vanilla JavaScript code compatible with all modern browsers
Arduino: not applicable (no hardware involved)