Ben Aston Ben Aston - 1 month ago 6
Javascript Question

Sending arguments when focussing an element

I am focussing an element in the DOM like so:

element.focus();


Presumably this is firing a focus event under the hood? Can I supply arguments with this by using a different syntax?

I have tried the following without success. I can use jQuery if need be:

$('.my-selector').trigger({
type: "focus",
options: 'argument1',
});


The handler is bound using angular
ng-focus
:

<input type="text" ng-focus="onFocus($event)"/>


The handler function:

function onFocus(evt) {
// I want to be able to distinguish events via state I pass
}

Answer

When using jQuery you can use

$('selector').trigger('event',[param1, param2,...])

and catch those with

$('selector').on('event', function(e, param1, param2, ..){..}

(as mentioned in http://api.jquery.com/trigger/#trigger-event-extraParameters)


Unfortunately this will not work with the focus event as documented in this bug report: Extra parameters are not passed when triggering focus

(note: it works in 1.8.3 and below, as mentioned in a linked/relevant bug report: focus event ignores additional data when triggered)