+ 1

I am lost (boxi problem)

You have 30 or so boxes. Once the user clicks on any one of them color of that particular box changes. I tried using event listeners but how do i know which box has been clicked. I know I could do something like: <div onclick="changeColor(box_number)"> but that's time consuming. Is there any other way to figure this out?

4th Aug 2018, 2:31 PM
Akib
Akib - avatar
10 Answers
+ 3
Make a common class for all the boxes. Create the event listener for all the same class. Link each event function with the respective element with bind function eg var boxes = document.getElementsByClassName("box"); for(i=0;i<totalBoxes;i++) { boxes[i].addEventListener("click", changeBackgroundColor.bind(boxes[i]), false); } } function changeBackgroundColor() { this.style.backgroundColor = "red"; } Check out the code here. https://code.sololearn.com/W4ilwd8fFyXu/?ref=app
4th Aug 2018, 3:39 PM
CalviŐ˛
CalviŐ˛ - avatar
+ 2
You can add an id on each box and check on the id of the clicked div.
4th Aug 2018, 3:06 PM
Jonathan Pizarra (JS Challenger)
Jonathan Pizarra (JS Challenger) - avatar
+ 2
Thanks calvin. Not sure I will be able to finish the whole engine in time. Its quite messy and big. But even if I don't finish it within the contest time once I'm done I will post in this thread and my feed. Have a great day/good night. (Its 10pm here though)
4th Aug 2018, 4:00 PM
Akib
Akib - avatar
+ 1
Calviղ you're too cool.😁😁 Thanks dude.
4th Aug 2018, 3:44 PM
Akib
Akib - avatar
0
Please add your code (js) in here, so I can see all that you have done and the first row of boxes, so I understand what that code looks like too. Once you've done that I'm certain I can help you as I can already imagine a few ways you like errored and that I can assist you.
4th Aug 2018, 3:01 PM
misterhtmlcss
misterhtmlcss - avatar
0
Stating the problem once again: You have 30/40 boxes similar to this example code. How would you know which box has been clicked. https://code.sololearn.com/W8C7FrF36ZLU/?ref=app
4th Aug 2018, 3:10 PM
Akib
Akib - avatar
0
Hi Akib, now that's helpful! thank you. So the first thing you want to do is wrap it inside a container div, that way you can add ONE event Listener to the parent which will then listen to clicks on its children. Do you know how to do that? Do that first and show me and I'll keep walking you through it so you actually learn it. Cool?
4th Aug 2018, 3:15 PM
misterhtmlcss
misterhtmlcss - avatar
0
misterhtmlcss In test box code if I clicked on any one of the boxes how would you know which one I clicked? And yes I know how to add event listeners.. This is just an example code. Don't wanna waste time here.
4th Aug 2018, 3:21 PM
Akib
Akib - avatar
0
Akib Reza Good luck..
4th Aug 2018, 3:56 PM
CalviŐ˛
CalviŐ˛ - avatar
- 1
hey plz see my question and give answer to it plz
4th Aug 2018, 5:38 PM
Rina Devi
Rina Devi - avatar