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 JavaScript and the DOM Responding to User Interaction The Event Object

Joshua Miller
Joshua Miller
7,824 Points

Is his solution more efficient?

His solution has an extra event handler, but mine has a loop which his doesn't. It his solution more efficient? Would this be an acceptable solution?

listWrap.addEventListener("mouseover", (event) => {
  for(let i = 0; i < listItems.length; i++){
    if(event.target == listItems[i]){
      listItems[i].textContent = listItems[i].textContent.toUpperCase();   
    } else {
      listItems[i].textContent = listItems[i].textContent.toLowerCase();      
    }
  }
});

2 Answers

Steven Parker
Steven Parker
208,478 Points

To determine "acceptable" you'd need some defined criteria to measure it with. This code does perform a function that is visibly similar to the code shown in the video, but it's not exactly the same. The original code would return the text to lower case if the mouse was moved off the list (such as at the beginning or end, or off the page entirely). But this code only changes the text to lower case if a different part of the div is being covered by the mouse.

In reference to efficiency, this code reassigns every list item's text when the mouse moves over any item, or over any other element in the div, or over the div itself. The code in the video only changes a single list item when the mouse moves over or away from it (so at most two at a time). Now these tasks happen fast enough that there won't be any difference in response noticed by the user, but this code certainly works much harder than the video code.

Joshua Miller
Joshua Miller
7,824 Points

Thanks for the explanation, makes total sense now why his solution is better.