-1

I have a function that I need to be called every time when my screen width is 1240px. What I mean is, for example, if I resize from 1300px or more to 1200px or less and as soon as it passes through 1240px my function should be called once. Same goes to, for example, if I resize from 1200px or less to 1300px or more and as soon as it passes through 1240px my function is being called once again.

that's what I tried:

function toggle() {
    toggle_time = setTimeout('toggle()', 1);
    if (document.body.offsetWidth<=1240) {
        myFunction();
    }
    if (document.body.offsetWidth>=1240) {
        myFunction();
    }
}

But it will call my function always and every millisecond what is wrong. Any answer is appreciated. Thanks !

2 Answers2

0
 function listenforwidth(width,callback){
  var store_width=0;
  window.onresize=function(){
   if((window.innerWidth>store_width && window.innerWidth>width )|| (window.innerWidth<store_width && window.innerWidth<width )){
        callback();
   }
   store_width=window.innerWidth;
   }

Use like this:

 listenforwidth(1024,function test(){
    window.test=null;
   alert("1024 passed");
 });
Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
-1

I'd rather use window.onresize event: https://developer.mozilla.org/fr/docs/Web/API/Window/onresize

So, something like:

function toggle() {
    if (document.body.offsetWidth<=1240) {
        myFunction();
    }
    if (document.body.offsetWidth>=1240) {
        myFunction();
    }
}

window.onresize = toggle;
Booster2ooo
  • 1,140
  • 8
  • 11
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/14891568) – RHA Jan 15 '17 at 14:26
  • Thanks, I'll keep that in mind. – Booster2ooo Jan 15 '17 at 14:37