user11600874
user11600874

Reputation:

How to run the script once at resize?

Suppose there are points for mob, tab and desk. mob is "<768" tab is "> = 768" and "<1024" desk is "> 1024"

It turns out when you reach the tab, you need to perform the function once, if the window has changed and become a mob, again you need to execute the function once, etc.

I did so

$(function() {
  var isDevice = "mob"; /* mob tab desk */

  $(window).on("resize", function() {
    var windowWidth = $(window).width();
    if (windowWidth < 768) {
      if (isDevice != "mob") {
        isDevice = "mob";
        console.log(isDevice);
      }
    } else if (windowWidth >= 768 && windowWidth < 1024) {
      if (isDevice != "tab") {
        isDevice = "tab";
        console.log(isDevice);
      }
    } else if (windowWidth >= 1024) {
      if (isDevice != "desk") {
        isDevice = "desk";
        console.log(isDevice);
      }
    }
  });
});

This works as expected, but maybe there is a better way to implement it?

link to codepen.io.

Upvotes: 1

Views: 93

Answers (1)

Rahi
Rahi

Reputation: 324

$(function() {
  var isDevice = "mob" /* mob tab desk */
  var doit;
  window.onresize = function(){
    clearTimeout(doit);
    doit = setTimeout(resizedw, 500);
  };   
});

function resizedw(){

 var windowWidth = $(window).width();
 //Implement logic here
    

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Related Questions