Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
215,357 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);