If you use a HTML form with placeholder texts, you will notice that select dropdowns always have a darker font color than the placeholder texts of the input fields. With this simple JavaScript snippet you can dynamically color the select dropdowns on change so that they behave more like normal text fields.
What does this pure JavaScript Code do?
// Make sure your DOM is loaded
document.addEventListener("DOMContentLoaded",function(){
// Find all select elements in the current DOM
const selects = document.querySelectorAll('select');
// Loop through all select elements
selects.forEach((elem, i) => {
// Add the class to make it look like a placeholder text
elem.classList.add('text-muted');
// Event listener to remove the class after selecting
elem.addEventListener('change',function(e){
// Remove the class to make it look normal (darker)
elem.classList.remove('text-muted');
});
});
});
Here's the working Example
Using the same Code without extra CSS
Of course you can use the same JavaScript Code without an extra CSS Class. Simply look at the next example:
// Make sure your DOM is loaded
document.addEventListener("DOMContentLoaded",function(){
// Find all select elements in the current DOM
const selects = document.querySelectorAll('select');
// Loop through all select elements
selects.forEach((elem, i) => {
// Change the style attribute to lighten the text color
elem.style.color = '#666';
// Event listener to change the style of the element
elem.addEventListener('change',function(e){
// Change the style attribute to darken the text color
elem.style.color = '#333';
});
});
});
That was easy!
Do you like this little trick? Feel free to use it for your projects. Write me a comment if you have any suggestions for improvement or further ideas.
Top comments (0)