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
  • 7,020
  • 4
  • 31
  • 51
user3358014
  • 97
  • 1
  • 9
  • What do you mean "it doesn't loop"? – Barmar Apr 14 '15 at 12:11
  • I'm still thinking about "it doesn't loop". The code *looks* well but we have to see these variable assignments. – kosmos Apr 14 '15 at 12:12
  • well when the second button displays it doesnt hide or display the other button onclick. just stops and the button doesnt trigger any events – user3358014 Apr 14 '15 at 12:13
  • @Barmar's answer is correct. You can replace `.css('display', 'block')` by `.show()` or `.hide()` in each case – kosmos Apr 14 '15 at 12:15

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
  • 741,623
  • 53
  • 500
  • 612
  • 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