Skip to content Skip to sidebar Skip to footer

Passing Parameters To $(window).on('resize') When Using .trigger('resize')

I need a reliable way to detect if $(window).on('resize') has been fired by user interaction or by a jQuery .trigger call. I've tried the following, but I don't seem to get the par

Solution 1:

You could try the following;

Javascript... on dom ready...

var $window = $(window);

$window.on('resize', function(event, param1) {

  console.log("Window resized event triggered by...");

  if (typeof param1 === 'undefined') // could also do if(param1) to test for falseconsole.log("System Event");
  elseconsole.log("User Event");

   // Another way to check is to check the originalEvent property// if (e.originalEvent === undefined) alert ('triggered by code');// else alert ('triggered by system');

});

setTimeout(function() {
  $window.trigger("resize", ["Custom"]);
}, 2000);

This is more or less what you were trying in your code, and it will distinguish the 2 types of events.

I also made a jsFiddle so you can see: https://jsfiddle.net/sysdevcode/4w3b8e14/

To make it work on your code

$(window).trigger('resize',[true]);

functionprepareOnResize(e, width, height, triggered){ console.dir(triggered); }
$(window).on('resize',prepareOnResize);

You need to change the order of the params on the prepareOnResize() function, as $(window).trigger('resize',[true]); equates to the [true] being sent as the "width" param in your function. you wold need to do, for instance:

var$window = $(window);
$window.trigger('resize',[ $window.width(), $window.height(), true ]);

then

function prepareOnResize(e, width, height, triggered){ ... }

will work, but if you don't need to pass any params, then the e.isTrigger of the code above is probably a bit more elegent.

Solution 2:

jQuery puts a property isTrigger in the event object, which you can test:

functionprepareOnResize(e){ 
    if (e.isTrigger) {
        console.log('resize via jQuery trigger');
    } else {
        console.log('resize by user');
    } 
}

Alternatively you can use e.originalEvent, which jQuery only the native event object has, as mentioned here:

functionprepareOnResize(e){ 
    if (!e.originalEvent)
        console.log('resize via jQuery trigger');
    } else {
        console.log('resize by user');
    } 
}

Post a Comment for "Passing Parameters To $(window).on('resize') When Using .trigger('resize')"