2

With the prevalence of using the CSS @media query, we can now style web pages based on the resolution on which they are viewed. The width-dependent style / layout will occur immediately when you resize the browser window. In CSS, this is pretty straightforward e.g.

// The heart of "responsive design."
@media screen and (max-width: 1000px) { ... }

In the spirit of responsive design, can we adjust a JavaScript logic on-the-fly upon resolution changes? For example, if we have script that outputs a number '5' every 10 seconds, can we alter it to output '7' (at the same interval) when the browser window is resized to <300px?

// Default script
setTimeout(function() {
  var i = 5;
  console.log(i);
}, 10000);

// How to change the value of i to 7, upon window resize?
// Ideally, without a page reload.
moey
  • 10,587
  • 25
  • 68
  • 112
  • If you are curious, I was trying to modify my carousel slider script that shows 3 image thumbnails, with a next button. A click to the button will advance 3 thumbnails. Now, when viewed on a smaller screen, I'd like to show only 1 thumbnail; and, the next button should advance 1 thumbnail at a time. – moey Aug 06 '12 at 14:53

3 Answers3

3

Handle the window.resize event:

window.onresize = function () {
    // check if the new height/width is <300
    // change your i variable
};

In order for this to work, your i variable must be in a scope that is shared by the resize handler and the anonymous you pass to setTimeout.

answer for Getting window height/width.

Community
  • 1
  • 1
jbabey
  • 45,965
  • 12
  • 71
  • 94
0

You can't accurately pass variables between CSS & JS, but Javascript exposes the resizeevent, which you can bind to the window.

For example:

function (event) {
  if (event.srcElement.outerWidth <= 1000 ){
    // do something
  }
}

Working JSFiddle Demo

briangonzalez
  • 1,606
  • 16
  • 21
0

If what you want is to show a number (based on the with) every 10 secs, the code is this one:

setInterval(function() {
    var num = (window.outerWidth <= 300) ? 7 : 5;
    console.log(i);
}, 10000);

If what you want is to show the number when the window is resized you should handle window.reseize event, as @jbabey answered.

Diego
  • 16,436
  • 26
  • 84
  • 136