Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot fire a mousedown event with jquery

I'm trying to simulate a click event in http://translate.google.com with jquery. For that purpose, I loaded jquery file with this code:

var script = document.createElement("script");
script.src = "http://code.jquery.com/jquery-1.10.1.min.js";
document.body.appendChild(script);

Then I'm trying to simulate a click on an element with a selector, like this:

jQuery(".goog-inline-block.goog-flat-menu-button-caption").trigger("mousedown")

I also tried this click event instead of mousedown:

jQuery(".goog-inline-block.goog-flat-menu-button-caption").trigger("click")

None of them gives the effect of manually clicking to the div, namely opening a new div. I attached the ss of desired behaviour.

clicked state

What can be the cause for jquery not working? Or how can I simulate the effect in any other ways?

Edit: Adding jQuery seems to be successful in the sense that I can use jQuery method to select elements and change contents of them etc.

like image 683
Behlül Avatar asked Sep 04 '13 09:09

Behlül


People also ask

What is Mousedown event in jQuery?

The mousedown event occurs when the left mouse button is pressed down over the selected element. The mousedown() method triggers the mousedown event, or attaches a function to run when a mousedown event occurs. Tip: This method is often used together with the mouseup() method.

How do I use Mousedown event?

To cause a MouseDown event for a form to occur, press the mouse button in a blank area or record selector on the form. To cause a MouseDown event for a form section to occur, press the mouse button in a blank area of the form section.

Is Mousedown the same as click?

Note: This differs from the click event in that click is fired after a full click action occurs; that is, the mouse button is pressed and released while the pointer remains inside the same element. mousedown is fired the moment the button is initially pressed.

Does Mousedown fire on mobile?

This works swimmingly on the desktop, but on mobile (testing in iOS Safari), the mousedown and mouseup events happen at the same time, so effectively nothing happens.


1 Answers

The solution was creating a MouseEvent and dispatching it to the element, like this:

var e1 = document.createEvent("MouseEvents");
e1.initMouseEvent("mousedown", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
jQuery('#gt-sl-gms')[0].dispatchEvent(e1)

It seems jQuery's event mechanism uses a different dispatching system, since it can not trigger the listener function, though I didn't confirm this info.

like image 61
Behlül Avatar answered Sep 27 '22 18:09

Behlül