Design comparison
Solution retrospective
Javascrip: I would like to simplify the 5 functions with an event ( "click") in just one if is posible. Could you help me with that?
Thanks a lot to everyone who spend time on reading me!!
Community feedback
- @erenymoPosted about 1 year ago
Hi Patricia👋
To solve your problem, please look at event delegation concept.
Marked as helpful0 - @better5afePosted about 1 year ago
Hi Patricia!
Firstly, congratulations on completing this project! I hope you had a lot of fun while making it! :)
To answer your question, there are two possible ways to shorten the event functions code:
-
standard for loop:
for (let i = 0; i < rate.length; i++) { rate[i].addEventListener("click", () => { valor = rate[i].innerHTML; }); }
-
forEach loop - it can be used as elements returned by the
getElementsByClassName
method are stored in a HTML Collection, which behaves similarly to an array:rate.forEach((element, i) => { element.addEventListener("click", () => { valor = rate[i].innerHTML; }); });
Hope it helps!
Happy coding! 🎃
Marked as helpful0@PatixiPosted about 1 year ago@better5afe thanks a lot! The first solution was what i was looking for!! I tried both but the second one send me an error (rate.forEach is not a function). Anyways you helped a lot!
1 -
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord