12

I can trigger click event on element selector using trigger

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

Is it possible to trigger shift click. I mean shift + left mouse click.

asked Mar 6, 2015 at 9:33
2
  • 2
    you mean do you want to programically create a shift+mouse click ? Commented Mar 6, 2015 at 9:57
  • 1
    @ArunprasanthKV exactly Commented Mar 6, 2015 at 9:59

3 Answers 3

16

try

var shiftClick = jQuery.Event("click");
shiftClick.shiftKey = true;
$("element selector").click(function(event) {
 if (event.shiftKey) {
 alert("Shift key is pressed");
 }
 else {
 alert('No shift hey');
 }
});
$("element selector").trigger(shiftClick);

JSFiddle

answered Mar 6, 2015 at 9:59
Sign up to request clarification or add additional context in comments.

Comments

0

You can check event.shiftKey boolean propery.

$("element selector").click(function(event) {
 if (event.shiftKey) {
 alert("Shift key is pressed");
 } 
});

Demo

answered Mar 6, 2015 at 9:37

1 Comment

thank you, but I need trigger not handler. Trigger is something that simulates shift click but not handle it.
0

Recently I tried the accepted solution using jQuery 4.0.0 BETA! (it's 2024, I know) to automate "shift + left click" interaction, but it's flaky in some cases for some reason. Not sure why. 🤷🏻 So I resorted to a more native solution below and it worked for me:

const elem = document.querySelector('button');
// Listen for the event.
elem.addEventListener('click', event => {
 if (event.shiftKey) {
 alert('shift key is pressed when clicked');
 return;
 }
 
 alert('shift key NOT pressed when clicked');
});
// Dispatch the event.
const shiftClickEvent = new MouseEvent('click', { shiftKey: true });
elem.dispatchEvent(shiftClickEvent);

https://jsfiddle.net/glenn/tw3uo5xd/

answered Apr 10, 2024 at 20:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.