tau
tau

Reputation: 6749

Fire jQuery live event with native JavaScript

I have an event on a page that I need to fire from a Chrome Extension. I do not have access to modify the page's JavaScript.

$(selector).live("click", fn);

I need to trigger this with native JS in my Chrome extension, like this:

selectorElement.click(); //doesn't work

Of course that above won't work because the live function is being used. How can I trigger it though?

Thanks!

Upvotes: 0

Views: 754

Answers (2)

apsillers
apsillers

Reputation: 115950

If you don't have jQuery, you can fire DOM events using dispatchEvent:

var selector = "#...";
var elmList = document.querySelectorAll(selector);

var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
elm[0].dispatchEvent(evt);

This code fires on the first element matching the selector, but it could be modified to loop over elmList if you needed to fire on several elements at once.

Upvotes: 4

Joseph
Joseph

Reputation: 119847

Have you tried trigger()?

$(selector).trigger('click');

Of course, trigger() should be used on a jQuery object (hence the $(selector)) .

Upvotes: 0

Related Questions