river rhun
river rhun

Reputation: 80

Javascript adding and deleting class wont work

i tried to build show and hide navigation to save more space. but after all i did, it became so jumpy. i can delete the show class and adding the the hide class but after that the hide class do nothing. please help.

<script>
    $(".servicesShowLink").click(function(){
            document.getElementById("servicesShow").className = "";
            document.getElementById("servicesShow").className = "servicesHideLink";
    });
    $(".servicesHideLink").click(function(){
            document.getElementById("servicesShow").className = "";
            document.getElementById("servicesShow").className = "servicesShowLink";
    });
    </script>

Upvotes: 0

Views: 63

Answers (2)

Matthew
Matthew

Reputation: 388

Using DomElement.classlist.toggle("servicesHideLink"); should solve your problem with one onclick event. I suspect the problem was that when you clicked, it toggled, and added a new event listener, which fired. As such it would make sense to use one event listener.

Upvotes: 1

trincot
trincot

Reputation: 350866

The selectors are evaluated once and produce a set of elements, then the event handler is bound to those element(s), but without knowing anything about the selector you used to get those elements. So even if the classes change, the elements do not, and the event handlers stay like they are.

You can use event delegation to get what you want:

$(document).on('click', ".servicesShowLink", function(){
     $("#servicesShow").removeClass("servicesShow");
     $("#servicesShow").addClass("servicesHideLink");
});
$(document).on('click', ".servicesHideLink", function(){
     $("#servicesShow").removeClass("servicesHideLink");
     $("#servicesShow").addClass("servicesShow");
});

I used the opportunity to suggest more jQuery-style code instead of the document.getElementById calls, ...etc.

Upvotes: 1

Related Questions