fruitjs
fruitjs

Reputation: 765

Avoid onresize and orientationchange both fires

In my existing application I am handling two events, one for change in orientation for mobile and onresize for desktop. unfortunately both events get fire.

I am trying to fire only one function whenever there is any change in device orientation or on browser resize. I want something like the example given below. Or Suggest me whatever I am missing here.

(function() {
  var getEvent = function() {
    event = window.ondeviceorientation || window.onresize;
    return event;
  };
  document.addEventListener(getEvent, function() {
    console.log("Size changed");
  }, false);

})();

JSBIN

Upvotes: 2

Views: 257

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138277

GetEvent is a function...

function() {
 var getEvent = function() {
    event = window.ondeviceorientation ? "deviceorientation" :  "resize";
    return event;
 };
 document.addEventListener(getEvent(), function() { //<---
  console.log("Size changed");
 }, false);

})();

And addEventListener requires a string, so you need to create a string. Shortified:

document.addEventListener(window.ondeviceorientation ? "deviceorientation" :  "resize", function() {
  console.log("Size changed");
 }, false);

This makes your code work but it either fires on deviceorientation or on resize. So you may want this:

function callable(){};
document.addEventListener("deviceorientation",callable);
document.addEventListener("resize",callable);

Upvotes: 2

Related Questions