0
$(document).ready(function () {
    $("#button").toggle(function () {
        $("#preview").animate({
            height: 940,
            width: 940
        }, 800);
        $("#button").replaceWith('<div id="button" style="margin:50px">Close</div>');
    }, function () {
        $("#preview").animate({
            height: 500,
            width: 500
        }, 800);
        $("#button").replaceWith('<div id="button" style="margin:0px">Open</div>');
    });
});

This makes the preview screen change size and changes the button, however it does not execute the second part of the toggle, which would be resize the preview back and change the button's value to the original state (Open).

Any idea how to fix this?

karthikr
  • 97,368
  • 26
  • 197
  • 188
Daan Twice
  • 337
  • 1
  • 3
  • 15
  • 2
    That's because you are replacing the element. Instead of that, change text contents. – Ram May 16 '13 at 14:49
  • Also i dont think toggle take 2 callbacks to execute alternatively. – PSL May 16 '13 at 14:51
  • are you using jQuery 1.8 +? if so this may help [link](http://stackoverflow.com/questions/14382857/what-to-use-instead-of-toggle-in-jquery-1-8) – Abraham Uribe May 16 '13 at 14:52

2 Answers2

2

The toggle() function used that way is deprecated and removed in the newest versions of jQuery. You'll have to create your own toggle functionality. Also, when replacing an element with a new one, the event handlers are lost :

$("#button").on('click', function() {
    var state = $(this).data('state');
    if ( state ) {
        $("#preview").animate({height: 500, width: 500 }, 800);
        state = false;
    }else{
        $("#preview").animate({height: 940, width: 940 }, 800);
        state = true;
    }
    $(this).text(state ? 'Open' : 'Close').data('state', state);
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

here's a working fiddle to accomplish what you want, using a different technique other than "toggle()". This technique uses a flag to set the state of the "open/close" button by adding and removing a class.

working fiddle:
http://jsfiddle.net/nY6UC/2/

jquery code:

$(document).ready(function () {

    $("#button").on("click", function () {

        if ($(this).hasClass("close")){

            $(this).removeClass("close");
            $(this).text("open");
            $("#preview").animate({
                height: 100,
                width: 100
            }, 800);
        }else{

            $(this).addClass("close");
            $("#preview").animate({
                height: 300,
                width: 300
            }, 800);
            $("#button").text("close");
        }
    });

});

css:

#button, #preview{     width: 100px;    height: 100px; }
#button {     background-color: red;}
#preview{     background-color: blue;}
carrabino
  • 1,742
  • 1
  • 14
  • 17