0

I have these two Jquery click events that will hide/display each other's buttons but it doesn't loop. Should i use Jquery 'toggle' event? thanks!!

        // Desktop onclick function to re-display first 2 drop down lists
        $editDeskBtn.on('click', function () {
            $disDeskSel1.fadeOut();
            $disDeskSel2.fadeOut();
            $firstTwoInputs
                .css("display", "block")
                .hide()
                .fadeIn();
            $editDeskBtn.replaceWith($saveDeskBtn);
            $saveDeskBtn.css("display", "block");

        });
        // *******************************************************************

    // Desktop onclick function for SAVE button
    $saveDeskBtn.on('click', function () {
        $firstTwoInputs.fadeOut();
        // show first two input results
        $disDeskSel1.fadeIn();
        $disDeskSel2.fadeIn();
        $saveDeskBtn.replaceWith($editDeskBtn);
        $editDeskBtn.css("display", "block");
    });
Peter
  • 6,640
  • 4
  • 29
  • 48
user3358014
  • 97
  • 1
  • 9

1 Answers1

1

The problem is your use of replaceWith. When you replace an element, all its event bindings are lost.

Instead of replacing elements, just keep both elements in the DOM, and use .hide and .show to show the one that you want.

$editDeskBtn.on('click', function () {
    $disDeskSel1.fadeOut();
    $disDeskSel2.fadeOut();
    $firstTwoInputs.hide().fadeIn();
    $editDeskBtn.hide();
    $saveDeskBtn.show();

});
// *******************************************************************

// Desktop onclick function for SAVE btn
$saveDeskBtn.on('click', function () {
    $firstTwoInputs.fadeOut();
    // show first two input results
    $disDeskSel1.fadeIn();
    $disDeskSel2.fadeIn();
    $saveDeskBtn.hide();
    $editDeskBtn.show();
});

I've also replaced all your .css calls with .show and .hide.

If you really need to use replaceWith, use event delegation as described in Event binding on dynamically created elements?

Community
  • 1
  • 1
Barmar
  • 669,327
  • 51
  • 454
  • 560
  • Thanks! yea thats great. The reason i used replace was because the buttons are bouncing in the parent container. i tried to use absolute positioning but it doesnt seem to work – user3358014 Apr 14 '15 at 12:16
  • If you really need to use replace, see the link to the question about event delegation. – Barmar Apr 14 '15 at 12:19