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

Wouldn't this code do the same thing? Works fine for me, is there a problem that I don't see?

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

messageTextArea.addEventListener('focus', () => {
  messageTextArea.className = 'highlight';
});

messageTextArea.addEventListener('blur', () => {
  messageTextArea.className = '';
}); ```

3 Answers

Hi there, Gafur Iusupaliev!

I guess I'm not sure what your question is. The focus event handler is to handle when a user focuses in on an element, and the blur event handler is when the user strays away from it.

Hopefully, that helps a bit, if not feel free to post another question that will help the community narrow in on your desired answer.

Thank you!

I'm comparing my code to the code in the video, I thought the video comes with the question, apparently it does not, that's not what I was asking, I appreaciate your asnwer either way!

yep working without param

const nameInput = document.getElementById('name');
const messageTextArea = document.getElementById('message');
const focuss= () => { event.target.className = 'highlight' ;}
const blurr= () => { event.target.className = '' ;}

nameInput.addEventListener('focus', focuss)
nameInput.addEventListener('blur',blurr)
messageTextArea.addEventListener('focus', focuss)
messageTextArea.addEventListener('blur', blurr)```

Alternatively you could also build in the "addEventListener" that way you can add a blur or focus event on any element like this:

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

const focusBlurHandler = (element, focusOrBlur)=>{
  let eventFlag = focusOrBlur;
  if(eventFlag.toLowerCase() == "focus"){ 
    element.addEventListener('focus',(e)=>{
    e.target.className= "highlight";
  });
  }else if (eventFlag.toLowerCase() == "blur"){
    element.addEventListener('blur',(e)=>{
    e.target.classList.remove("highlight");
    });
  }
}


focusBlurHandler(nameInput,"focus");
focusBlurHandler(nameInput,"blur");
focusBlurHandler(messageTextArea,"focus");
focusBlurHandler(messageTextArea,"blur");