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 trialRyan Soeder
11,056 PointsIs 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
231,275 PointsAs 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'));
Jesse Cleary-Budge
Front End Web Development Techdegree Graduate 15,359 PointsJesse Cleary-Budge
Front End Web Development Techdegree Graduate 15,359 PointsOn this theme, I created my own toggler that relies on the
classList.add()
andclassList.remove()
methods. Thought I'd share it here. :D