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);
}
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);
}
Share
Improve this question
asked Feb 4, 2016 at 1:03
user90726user90726
9751 gold badge10 silver badges33 bronze badges
0
1 Answer
Reset to default 8Update: 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/zqdftehw/2/
References:
https://developer.mozilla/en-US/docs/Web/API/MouseEvent/initMouseEvent http://marcgrabanski./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/en/docs/Web/Events/click
JSFiddle: https://jsfiddle/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.