function openSubMenu() { $('.work-examples__li').each(function () { testingByNik(); }); function testingByNik() { $(this).on("click", function () { //var tarGet = $(".work-examples .example.view-project-first"); //var activeBlock = $(".first .work-examples__li_active"); var tarGet = $(this).find(".example"); var activeBlock = $(this).find(".work-examples__li_active"); $(".projects__content .work-examples .example:not('.view-project-first')").removeClass("pop-up"); $(".projects__content .work-examples .work-examples__li_active:not('.first')").removeClass("visible"); if (!tarGet.hasClass('pop-up') && !activeBlock.hasClass('visible')) { tarGet.addClass('pop-up'); activeBlock.addClass('visible'); } else { tarGet.removeClass('pop-up'); activeBlock.removeClass('visible'); } }); } } 

And so, for each .work-examples__li I perform the function testingByNik This function is executed when I click on .work-examples__li . Next tarGet is .work_examples__li .example , a .activeBlock is .work-examples__li .work-examples__li_active. Right?

  • Judging by the code, you testingByNik not testingByNik for each .work-examples__li , but just so many times. Because you do not associate the function call and the elements found. - Alexey Ten
  • $('.work-examples__li').each(testingByNik) - Grundy
  • @Grundy thanks, your version has earned - Nikita Shchypylov

1 answer 1

This function is executed when I click ...

No, this function is executed when you call it. On click, a click event handler is executed - an anonymous function in

 $(this).on("click", function () { ... }); 

Judging by the code inside testingByNik , you expect that the context for it will be one of the elements '.work-examples__li' . In your code, this is not the case - you call it in the global context window .

You can do this:

 $('.work-examples__li').each(function () { testingByNik.call(this); }); 

But there is no need for your cycle. For all selected items you do the same thing.

 $('.work-examples__li').on("click", function () { //var tarGet = $(".work-examples .example.view-project-first"); //var activeBlock = $(".first .work-examples__li_active"); var tarGet = $(this).find(".example"); var activeBlock = $(this).find(".work-examples__li_active"); $(".projects__content .work-examples .example:not('.view-project-first')").removeClass("pop-up"); $(".projects__content .work-examples .work-examples__li_active:not('.first')").removeClass("visible"); if (!tarGet.hasClass('pop-up') && !activeBlock.hasClass('visible')) { tarGet.addClass('pop-up'); activeBlock.addClass('visible'); } else { tarGet.removeClass('pop-up'); activeBlock.removeClass('visible'); } }); 
  • Thanks for the answer. I have nine .work-examples__li blocks and, when clicked, I need to do the handler only to the one I clicked on. That's the idea - Nikita Shchypylov