Removing the $(window).resize Event in jQuery

BiscuitBaker picture BiscuitBaker · Nov 7, 2012 · Viewed 48.4k times · Source

Part of the page I'm developing requires a $(window).resize event to be added to a div when a user clicks a button, in order to toggle between resizing it with the window and leaving it fixed at its original size:

function startResize() {
    $(window).resize(function() {
        $("#content").width(newWidth);
        $("#content").height(newHeight);
    });
}

What I can't work out is how to "turn off" this event when the button is clicked again, so that the content stops resizing.

function endResize() {
    // Code to end $(window).resize function
    $("#content").width(originalWidth);
    $("#content").height(originalHeight);
}

Any help with this would be greatly appreciated.

Answer

Esailija picture Esailija · Nov 7, 2012
function endResize() {
    $(window).off("resize");
    $("#content").width(originalWidth);
    $("#content").height(originalHeight);
}

Note that this is extremely obtrusive and might break other code.

This is better way:

function resizer() {
    $("#content").width(newWidth);
    $("#content").height(newHeight);
}

function startResize() {
    $(window).resize(resizer);
}

function endResize() {
    $(window).off("resize", resizer);
}