0

i am trying to activate a jQuery 'replaceWith' function on click to replace div1 with div2 and then use 'replaceWith' again to replace div2 with div1 on click.

everything is working except, when clicking on div2, div1 does not re-appear.

my code is:

$(document).ready(function(){
$("#open_doors").click(function(){
$("#leftdoor_inner").animate({"left": "-=164px"}, 'slow');
$("#leftdoor_outer").animate({"left": "-=74px"},'slow');
$("#rightdoor_inner").animate({"left": "+=164px"},'slow');
$("#rightdoor_outer").animate({"left": "+=74px"},'slow');
$("#open_doors").replaceWith($("#close_doors"));
});
$("#close_doors").click(function(){
$("#leftdoor_inner").animate({"left": "+=164px"},'slow');
$("#leftdoor_outer").animate({"left": "+=74px"},'slow');
$("#rightdoor_inner").animate({"left": "-=164px"},'slow');
$("#rightdoor_outer").animate({"left": "-=74px"},'slow');
$("#close_doors").replaceWith($("#open_doors"));
});
});​

the nearly working jsfiddle is here:

http://jsfiddle.net/9zsdN/2/

i'm pretty sure my question has been answered at the link below but i can't figure out how to apply it to my exact code.

Events not registering after replaceWith

thank you.

Community
  • 1
  • 1
user1063287
  • 10,265
  • 25
  • 122
  • 218
  • The problem has nothing to do with events. When you replace div1 with div2, div1 no longer exists, so the second replacement replaces with nothing. – Barmar Oct 25 '12 at 08:58

1 Answers1

3

instead of replaceWith you can just use show() and hide()

 $(document).ready(function(){
      $("#open_doors").click(function(){
        $("#leftdoor_inner").animate({"left": "-=164px"}, 'slow');
        $("#leftdoor_outer").animate({"left": "-=74px"},'slow');
        $("#rightdoor_inner").animate({"left": "+=164px"},'slow');
        $("#rightdoor_outer").animate({"left": "+=74px"},'slow');
        $("#open_doors").hide();
        $("#close_doors").show();
      });
     $("#close_doors").click(function(){
         $("#leftdoor_inner").animate({"left": "+=164px"},'slow');
         $("#leftdoor_outer").animate({"left": "+=74px"},'slow');
         $("#rightdoor_inner").animate({"left": "-=164px"},'slow');
         $("#rightdoor_outer").animate({"left": "-=74px"},'slow');
         $("#close_doors").hide();
         $("#open_doors").show();
     });
   });

Demo

YogeshWaran
  • 2,291
  • 4
  • 24
  • 32