javascriptjqueryjquery-eventsjquery-trigger

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 parameters back in the function call:

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

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

Triggered seems to return the width of the screen, so I tried the following, also to no avail:

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

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

In that instance triggered comes back undefined.

I'm at a loss here -- any help would be greatly appreciated.


Solution

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

    function prepareOnResize(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:

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