简体   繁体   中英

Removing the $(window).resize Event in jQuery

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.

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);
}
function startResize() {
   $(window).on("resize.mymethod",(function() {
     $("#content").width(newWidth);
     $("#content").height(newHeight);
   }));
}

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

using a namespace on the query method will allow to to turn off the resize event for you method only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM