23

Just wondering if there is any way to trigger a Ctrl + CLICK (or just any key + CLICK) in jQuery. I am thinking of something like the following:

var e = jQuery.Event("keydown");
e.which = 17;
$('a.'+id, this._parent).trigger(e).trigger('click');

or

var e = jQuery.Event("click");
e.ctrlKey = true;
$('a.'+id, this._parent).trigger(e);

Thank you!

udondan
  • 57,263
  • 20
  • 190
  • 175
Cricri
  • 1,524
  • 3
  • 12
  • 17
  • For what purpose? Triggering a click in JS won't fire off a hyperlink, for instance. – Grim... Feb 21 '12 at 11:49
  • 2
    I think it's always better to trigger the RESULT of an action than action itself: change window.location instead of clicking anchor with JS, for example. –  Feb 21 '12 at 11:53
  • I am using a web control which is a column view (similar to the OSX Finder - see 'http://christianyates.com/comment/1529' for more details). I want to select items in this column view on page load (part of coming back to what the user has selected before) and I am doing this currently by triggering CLICK on elements in the column view. One column can have multiple elements selected and that would be done with CTRL+CLICK. So the why I want to trigger that event. – Cricri Feb 21 '12 at 11:56
  • [http://christianyates.com/comment/1529] link again. – Cricri Feb 21 '12 at 11:58
  • 1
    Yeah, instead of trying to emulate the click, just add the targets to the set of selected elements. – JJJ Feb 21 '12 at 12:56
  • Guess the lazy side of me wanted an easy way out. :) Thank you for all your input. Will do what was suggested. – Cricri Feb 21 '12 at 14:37
  • triggering the result doesn't work if you try to modify a website behaviour by script injection using Tampermonkey. Also Ctrl+click opens in new tab there might be a 'trigger' solution for that, but basically I want to achieve whatever the configured browser behaviour is for ctrl+click. – Daniel Jul 29 '15 at 07:34

1 Answers1

21

yes this will work for you:

var e = jQuery.Event("click");
e.ctrlKey = true;
$('#id').trigger(e);
galzalait
  • 231
  • 2
  • 6