Search code examples
javascriptjqueryhtmlcsstoggleclass

JS toggleClass right way


I've this project where when I click on the plant the scale changes and show some texts.

http://www.gaianet.com.br/Nissin-teste/

I've this project where I should click on a planet and scale's it and show another div by opacity.

Right now i've been trying to do by js using toggle class but I need some help to make it work right.

If I click on first planet it works fine, but when this planet is 'selected'and I click on another all the classes start to toogle and the scale and opacity goes crazy.I don't know how to make a 'reset' to the original css if I click on another planet when one has already changed the class.

$(".layer.planeta1").click(function(){
  $(".institucional").toggleClass("escala-planeta repo1-1");
   $(".planet-info1").toggleClass("opacidade-planeta ");
    $(".educacao").toggleClass("escala-menor-planeta repo1-2");
     $(".pdv").toggleClass("escala-menor-planeta repo1-3");     
}); 



$(".layer.planeta2").click(function(){
  $(".educacao").toggleClass("escala-planeta repo-2-1");
   $(".planet-info2").toggleClass("opacidade-planeta ");
    $(".institucional").toggleClass("escala-menor-planeta repo-2-2");
     $(".pdv").toggleClass("escala-menor-planeta repo-2-3");       

}); 



$(".layer.planeta3").click(function(){
  $(".pdv").toggleClass("escala-planeta");
   $(".planet-info3").toggleClass("opacidade-planeta ");
     $(".educacao").toggleClass("escala-menor-planeta");
     $(".institucional").toggleClass("escala-menor-planeta");         
}); 

I'm sure there should a way better way to do that but I have no idea how. Thanks a lot


Solution

  • I think I am clear on the acceptance criteria, but just to be sure, here is what I am going with:

    • When I click on a planet, I want it to scale.
    • If I click on a planet that is already scaled, I want it to reset to original scale.
    • When I click on a planet, I want to 'reset' any other planets to their original scale, and scale the planet I clicked on if it is not already scaled.

    Given that, you might try being more explicit about what needs to happen when you click on a 'planet':

    $('.planet').on('click', function(event){
      $('.planet').removeClass('scale');  // Explicitly remove the scale class from other planets
      $(this).toggleClass('scale'); // Scale the one I am clicking on, or if it's already scaled, revert it
    });
    

    A simplified example demonstrating this: http://codepen.io/anon/pen/xbMJRd