Worm
Worm

Reputation: 1451

Get the change of dimensions on resize using jQuery

For my web site I am using the following code:

$(window).resize(function (event) {
    window.location.reload();
});

Unfortunately when using the site on a mobile device there are minute resize events that occur. I am wanting to put in a tolerance so that these minute changes do not fire this reload.For this I need to know the change in dimensions that occurred in the resize event. I have been looking at the event object however it is huge and ugly.

Thanks in advance :)

Upvotes: 4

Views: 341

Answers (2)

Worm
Worm

Reputation: 1451

Building on the helpful comments of JBDouble05 and the helpful answer by Dacre Denny I have made a final solution that fits my needs. Here it is to help others in the future hopefully.

var OGwidth = $(window).width();
var OGheight = $(window).height();
var threshold = 50;
$(window).resize(function (e) {
    if (OGwidth < 768) {
        var newWidth = $(window).width();
        var newHeight = $(window).height();

        var widthChange = Math.abs(OGwidth - newWidth);
        var heightChange = Math.abs(OGheight - newHeight);

        if (widthChange > threshold || widthChange > threshold) {
            window.location.reload();
        }

    } else {
        window.location.reload();
    }
    //reset for next resize
    OGwidth = newWidth;
    OGheight = newHeight;
})

Upvotes: 0

Dacre Denny
Dacre Denny

Reputation: 30400

You could achieve this by tracking the original window dimensions and then comparing those dimensions with current dimensions (acquired during each resize event) to determine the amount of change.

The following shows how you could trigger a reload if the width changes by a certain total THRESHOLD amount:

var THRESHOLD = 50; // the threshold that must be exceeded to trigger reload

$(window).resize(function(e) {

  var width = $(window).width();

  // Record the starting window width that the comparison will
  // be relative to
  if(window.startWidth == undefined) {
    window.startWidth = width;
  }

  // Calculate the total change since first resize event
  var widthChange = Math.abs(width - window.startWidth);

  // If change exceeds THRESHOLD, trigger reload
  if(widthChange > THRESHOLD) {
    window.location.reload();
  }

})

Upvotes: 2

Related Questions