Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate shift-mouseclick

Is there a way to somehow simulate Shift+Click?

This code works quite well, but currently, without shift:

//--- Get the first link that has "stackoverflow" in its URL.
var targetNode = document.querySelector ("a[href*='stackoverflow']");
if (targetNode) {
    //--- Simulate a natural mouse-click sequence.
    triggerMouseEvent (targetNode, "mouseover");
    triggerMouseEvent (targetNode, "mousedown");
    triggerMouseEvent (targetNode, "mouseup");
    triggerMouseEvent (targetNode, "click");
}

function triggerMouseEvent (node, eventType) {
    var clickEvent = document.createEvent ('MouseEvents');
    clickEvent.initEvent (eventType, true, true);
    node.dispatchEvent (clickEvent);
}
like image 716
user90726 Avatar asked Feb 04 '16 01:02

user90726


1 Answers

Update: If you want to trigger shift+click event, you can see this post

shift mouse click trigger

If you want to simulate shift+click, then you should use initMouseEvent instead of initEvent. Check the following fiddle.

https://jsfiddle.net/zqdftehw/2/

References:

https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/initMouseEvent http://marcgrabanski.com/simulating-mouse-click-events-in-javascript/

If you want to know whether shift key is pressed or not, then the following will work,

<div id="test"></div>

<script>
  document.getElementById("test").addEventListener("click", function( event ) {
    if (event.shiftKey) {
        console.log('shift pressed');
    } else {
        console.log('shift not pressed');
    }
  }, false);
</script>

Reference: https://developer.mozilla.org/en/docs/Web/Events/click

JSFiddle: https://jsfiddle.net/zqdftehw/1/

Note: Both initEvent and initMouseEvent are deprecated, so you might want to use jQuery solution provided in the other stack overflow answer (link mentioned above) to be on safer side.

like image 85
Kishor Avatar answered Oct 04 '22 20:10

Kishor