K
K
Kryptonit2020-05-12 18:43:27
JavaScript
Kryptonit, 2020-05-12 18:43:27

How to do it in PURE js?

I need to hang a click event handler on each li from the ul menu:
(not stupidly on each individual element)

<ul class = "list">
                    <li class="li active">главная</li>
                    <li class="li">навыки</li>
                    <li class="li">опыт</li>
                    <li class="li">портфолио</li>
                    <li class="li">контакты</li>
                </ul>

There are answers on the forums, but, in my opinion, they are few and often there is no explanation.
Subsequently, this html will be used to create anchor links to js. (I'm not satisfied with html for a number of reasons).
Please attach the code with a clear explanation

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vearodev, 2020-05-12
@Kryptonit

Delegation Example

Or through a loop, for each individual element

S
Stas Khitrich, 2020-05-12
@Snova_s_vami

Here is a small sandbox example using old JavaScript.
Link to the sandbox
I don’t advise hanging on each element of the list, because there can be a lot of them and this will have a bad effect on performance, so there is such a thing as event delegation, this is when we hang 1 listener on the parent element and check where the click was made. This is exactly what is done in the sandbox example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question