0

Trying to create a "hello world" alert that fires whenever the the browser window hits 1200px.

Example: Scroll from 1220 to 1100 pixels: event fires once at 1200. Example: Scroll from 1100 to 1220 pixels: even fires once at 1200.

Any help would be appreciated.

This is what I have been working with (for the most part)

window.onresize = function ()
    {
        if (window.innerWidth = 1199) {
           //alert ("The size of the window is 1199");
          location.reload();
          return;
        }

  }

This is the cleaned up code. I don't believe == or === make a difference in this case

 window.onresize = function ()
    {
      if (window.innerWidth === 1199) {
         alert ("The size of the window is 1199");
      }
  }
newneub
  • 183
  • 1
  • 14
  • 2
    `window.innerWidth` is read-only ... After fixed that, most likely at the time you read the value, it's something else than 1199. You need a gap. – Teemu Jan 22 '16 at 21:33
  • 6
    Use '==' in your if statement – rosscj2533 Jan 22 '16 at 21:33
  • @rosscj2533 Actually, in javascript isn't it '==='? – kairocks2002 Jan 22 '16 at 21:38
  • @KaiChristensen - either will work in this case, but there are some differences to be aware of – rosscj2533 Jan 22 '16 at 21:41
  • 2
    You also don't need an empty `return`. All JavaScript functions return `undefined` by default if you don't specify a `return ` – Matthew Herbst Jan 22 '16 at 21:41
  • `if (window.matchMedia("(max-width: 1200px)").matches) {...}` [doc](https://developer.mozilla.org/en/docs/Web/API/Window/matchMedia) **&** [polyfill](https://github.com/paulirish/matchMedia.js/) – A. Wolff Jan 22 '16 at 21:43
  • 1
    @MatthewHerbst `You also don't need an empty return` ya, especially after `location.reload();` is called – A. Wolff Jan 22 '16 at 21:48
  • Looks like the question is actually more complex than it looks like. We don't know, if OP want's to detect 1200 when resizing the window to smaller or bigger. Or both? @newneub How is it? Both directions, or just increase/decrease the size? – Teemu Jan 22 '16 at 21:51
  • @Teemu Updated example to explain more clearly what I am trying to achieve – newneub Jan 22 '16 at 21:57
  • Yep, now we know, that both resizing directions should trigger redirection. This is achievable within some size of a gap, but not exactly. Would it do, if the size would be detected only when user has finished resizing? Or is it mandatory to refresh immediately when the border is acrossed? – Teemu Jan 22 '16 at 22:04
  • refreshing at the end of the resize would be great! I would just like it called at 1200 even if it fires when the user is done resizing the window. – newneub Jan 22 '16 at 22:21

4 Answers4

4

The resize event is not fired as often as you'd like in order to identify a window hitting an exact width of 1199 reliably while a user resizes.

e.g.

window.onresize = function() { console.log(window.innerWidth); }

To see the granularity.

To account for the lossy event notifications you could detect any resizing through the threshold value. This could still miss some resizing around the threshold, but should pick up the aggregate change of resizing:

var thresholdWidth = 1199;
var previousWidth = window.innerWidth;
window.onresize = function() {

  var movedUpThroughThreshold = previousWidth < thresholdWidth &&
    window.innerWidth >= thresholdWidth;
  var movedDownThroughThreshold = previousWidth >= thresholdWidth &&
    window.innerWidth <= thresholdWidth;

  if (movedUpThroughThreshold || movedDownThroughThreshold) {
    console.log("passed threshold", previousWidth, "->", window.innerWidth)
  }

  previousWidth = window.innerWidth;
}

Compatibility Note You'll need to account for innerWidth availability if you need to target IE8 and there may be wrinkles in various user agents though the standard describes innerWidth as being the viewport width, including the scrollbars.

Where innerWidth is not available you'll likely need to use the documentElement or body as a proxy for the viewport, but you'll need to make sure those are filling the viewport but not exceeding it.

mczepiel
  • 711
  • 3
  • 12
0

Try changing window.innerWidth = 1199 to window.innerWidth === 1199. I don't know if that will help, but it's worth a shot.

kairocks2002
  • 436
  • 1
  • 3
  • 15
0

Try this

window.onresize = function ()
{
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    if (w === 1199) {
       alert ("The size of the window is 1199");
      location.reload();
      return;
    }

}

Mohammed Raja
  • 207
  • 2
  • 9
0

In a comment you've said, that refreshing after resize is OK. To achieve this, you need a debouncer. Debouncer is a function, which checks, if an event hasn't fired after a given delay, and only then it fires the event handler you've passed for the event. Like so:

var oldSide = window.innerWidth - 1200; // Stores positive value, if current size is greater than 1200, else zero or negative

// This is the debouncer, it delays the execution of the given handler untill user stops resizing
function debounce(fn, delay) {
   var delayId, delay = delay || 200;
   return function () {
      var scope = this, args = arguments;
      clearTimeout(delayId);
      delayId = setTimeout(function () {
          fn.apply(scope, Array.prototype.slice.call(args));
      }, delay);
   }
}

// Here we add the resize listener, notice, that we call the debouncer, and pass our actual handler to that
$(window).resize(debounce(function (e) {
    var newSide = window.innerWidth - 1200;
    // newSide * oldSide is negative, if 1200 is acrossed in either directions during the last resizing
    if (newSide * oldSide <= 0) {
        // Window size acrossed 1200 during the last resize, refresh the page
    }
    // Window size didn't across 1200 during the last resize, set a new value to oldSide, and keep listening
    oldSide = newSide;
}));

A working demo at jsFiddle (logs only to console, no refresh).

Notice, that if you're not going to actually refresh when 1200 is acrossed, you must to return from the if block.

You can also detect the "border across" in the debouncer (just after clearTimeout), that way it will be more real time, but might have a gap of few pixels.

The debouncer I've used here originates to BGerrissen's great answer at SO.

Community
  • 1
  • 1
Teemu
  • 22,918
  • 7
  • 53
  • 106