Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 274
BiscuitBaker Avatar asked Nov 07 '12 11:11

BiscuitBaker


People also ask

How does jQuery determine window resize?

$(window). on('resize', function(){ var win = $(this); //this = window if (win. height() >= 820) { /* ... */ } if (win.

What happens when the window is resized?

The resize event fires when the document view (window) has been resized. This event is not cancelable and does not bubble. In some earlier browsers it was possible to register resize event handlers on any HTML element.

How do I resize a browser window in HTML?

The resizeTo() method is used to resizes a window to the specified width and height. Parameter Values: width: Sets the width of the window, in pixels. height: Sets the height of the window, in pixels.


2 Answers

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);
}
like image 159
Esailija Avatar answered Oct 21 '22 11:10

Esailija


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.

like image 36
arin Avatar answered Oct 21 '22 10:10

arin