Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

addEventListener

Hi,

I'm working on the JavaScript and the DOM and I'm trying out something to make a more interactive contact form.

My question is, if there is a better way to write this code?

It's a standard form with 4x input fields inside

const inputs = document.querySelectorAll('input');

for (let i = 0; i < inputs.length; i++) {
  inputs[i].addEventListener('focusin', () => {
    inputs[i].style.backgroundColor = 'white';
  });
  inputs[i].addEventListener('focusout', () => {
    if (inputs[i].value == '') {
      inputs[i].style.backgroundColor = '#ccc';
    }
  });
}
<form>
    <label for="fName">First name:</label>
    <input type="text" id="fName">
    <label id="noFirstName"></label>

    <label for="lName">Last name:</label>
    <input type="text" id="lName">
    <label id="noLastName"></label>

    <label for="email">Email:</label>
    <input type="email" id="email">
    <label id="noEmail"></label>

    <label for="password">Password:</label>
    <input type="password" id="password">
    <label id="noPassword"></label>

    <button type="button" id="submit">Send</button>
  </form>

1 Answer

Steven Parker
Steven Parker
243,656 Points

Your code is clean, concise, and easily readable. Good job! :+1:

My only suggestion would be to consider using CSS instead of JavaScript to do the same job, and to also give the fields the "blur" ("focusout") appearance initially so the effect can be seen right away.

input { background-color: #ccc; }
input:focus { background-color: white; }

Thank you very much for the advice :-)

I found the blur (event?) maybe an hour after I made this post and replaced it - and the reason for doing it in JS instead of CSS was mainly just to learn JS since I've been jumping around between languages / frameworks (which is a bad idea as a 'newbie', hehe) and never really learned all these cool things :-)

If something can be done in CSS then it should be done in CSS? or are there exceptions where you want to do it in JS instead?