I'm trying to calculate the percentage that the browser was resized but I can't seem to capture the size of the window before the resize began and then the size after it finishes.
$(function () {
var originalHeight = $(window).height();
$(window).resize(function (e) {
var newHeight = $(window).height();
var percentageChange = newHeight / originalHeight;
$('body').html('old: ' + originalHeight + ' | new: ' + newHeight);
originalHeight = newHeight;
});
});
The two numbers (originalHeight and newHeight) always match for some reason. Is there something I can to to simulate two additional events such as beginResize
or endResize
? If I could do that then I could do this:
$(function () {
var originalHeight;
$(window).beginResize(function () {
originalHeight = $(window).height();
});
$(window).endResize(function () {
var newHeight = $(window).height();
var percentageChange = newHeight / originalHeight;
alert(percentageChange);
});
Any ideas?
Update:
I was able to duplicate this locally in a blank environment, but not on jsfiddle. I can only conclude that the iframe environment on jsfiddle is interfering.
When I execute the following page:
<!DOCTYPE html>
<html>
<head>
<title>Isolate</title>
<script type="text/javascript" src="~/Scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function () {
var originalHeight = $(window).height();
$(window).resize(function (e) {
var newHeight = $(window).height();
var percentageChange = newHeight / originalHeight;
$('body').append('old: ' + originalHeight + ' | new: ' + newHeight + ' | percentage: ' + percentageChange + '<br />');
originalHeight = newHeight;
});
});
</script>
</head>
<body>
</body>
</html>
I get the following results:
old: 417 | new: 418 | percentage: 1.0023980815347722
old: 418 | new: 418 | percentage: 1
old: 418 | new: 419 | percentage: 1.0023923444976077
old: 419 | new: 419 | percentage: 1
old: 419 | new: 420 | percentage: 1.0023866348448687
old: 420 | new: 420 | percentage: 1
old: 420 | new: 422 | percentage: 1.0047619047619047
old: 422 | new: 422 | percentage: 1
old: 422 | new: 423 | percentage: 1.0023696682464456
old: 423 | new: 423 | percentage: 1
It seems that the resize event is running twice for every resize. First time it detects a difference between original and new, but second time the values are the same because the first run updates originalHeight to the newHeight.
You can see in this fiddle that this double event run problem does not occur. Each entry shows different values for old and new.