river rhun river rhun - 3 months ago 14
CSS Question

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>

Answer

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.