Opinions wanted for Events Skill Test 3

Hi there! have just covered the “introduction to events” and tried the skill tests.
I’ll appreciate any opinions on the third portion.


Thanks

Welcome back, @texas-triumph

Your solution is correct. Instead of e.currentTarget you could also just use container, because the current target is always the element where the event gets attached to.

Michael

Hello Michael,
Thanks for the hint. To be honest ‘Introduction to events’ has been tough compared to everything I’d seen before it. The nature of the subject is more complex for comprehension and demands time. I corrected the code as you suggested and it did work which led me to think it over and see that there was some lack of understanding in utilizing e.currentTarget and e.target. Assigning the e.currentTarget I aimed at versatality of applicaton for my code, I thought I could apply this function to any elements’ bundle of the same type and it would produce the same effect, whereas an explicit assignment to the ‘container’ was solely dedicated to that particular element. Though I have to admit that I failed to make it in a form of a named function (a cliche) which I could then run to any other structure of elements. I reworked the code to test this logic. I’ll appreciate your opinion on this aspect.

Yes, that’s correct. It’s a way to reuse the event handler function. You could rewrite your code to

const container = document.querySelector('.button-bar');
const container1 = document.querySelector('.button-bar1');
container.addEventListener('click', run);
container1.addEventListener('click', run);

function run(e) {
  e.currentTarget.style.backgroundColor = e.target.getAttribute('data-color');
}

and it would still work as expected. currentTarget is especially useful when you’re attaching event handlers in a loop. currentTarget will then refer to the specific element and you only have to write the handler function once. There’s an example on the MDN article about Event.currentTarget.