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 Callback Functions in JavaScript Callbacks and the DOM Using the Same Callback on Multiple Elements

Is classList.toggle() ok here?

I used this and it seems to work well:

const nameInput = document.getElementById('name');
const messageTextArea = document.getElementById('message');

function toggleHighlight(event) {
  event.target.classList.toggle('highlight');
}

nameInput.addEventListener('focus', toggleHighlight);
nameInput.addEventListener('blur', toggleHighlight);

messageTextArea.addEventListener('focus', toggleHighlight);     
messageTextArea.addEventListener('blur', toggleHighlight);

Are there any issues I should be aware of?

1 Answer

Steven Parker
Steven Parker
231,236 Points

As in your [previous question], this is another case where you might want the event to control the adding or removing of the class directly to make sure that the state never gets out of sync with the class:

nameInput.addEventListener('focus', event => event.target.classList.add('highlight'));
nameInput.addEventListener('blur', event => event.target.classList.remove('highlight'));

On this theme, I created my own toggler that relies on the classList.add() and classList.remove() methods. Thought I'd share it here. :D

const nameInput = document.getElementById('name');
const messageTextArea = document.getElementById('message');

const toggleHandler = e => {
  const target = e.target;
  if ( target.classList.contains('highlight') ) {
    target.classList.remove('highlight');
  } else {
    target.classList.add('highlight');
  }
};

nameInput.addEventListener( 'focus', toggleHandler);
nameInput.addEventListener( 'blur', toggleHandler);

messageTextArea.addEventListener( 'focus', toggleHandler);
messageTextArea.addEventListener( 'blur', toggleHandler);