Mark Mark - 2 months ago 7
HTML Question

Move div onclick and back onclick

I have a jQuery code that moves a certain div element on right as I click it, i'd like to move it back to its original position when I click back on it.

$(document).ready(function() {
$("#wel1").click(function() {
$("#sidemenu").animate({left: "80px"});
});
});


Give me a simple example of how to achieve it?

Answer

One possible way to achieve it is to store the state in a variable and check its state on click.

$(document).ready(function() {
   var sideMenu = false;
    $("#wel1").click(function() {
      if (!sideMenu) {
        $("#sidemenu").animate({left: "80px"});
        sideMenu = true;
      }
      else {
        $("#sidemenu").animate({left: "0px"});
        sideMenu = false;     
      }
    });
}); 

Please be aware that this solution has several issues:

  • will not work for multiple menus
  • can produce unwanted animation effects ("jumping") if quickly clicked
Comments