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
203,151 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.