2

I know there are ways to detect an alt-click, but I'm curious- is it possible to alt-click an element?

You could call the function that the click event calls, but just say hypothetically we're dealing with some system that dynamically generates the function and places it in the page as it is rendered (or some other wild explanation).

Oliver
  • 2,182
  • 5
  • 24
  • 31
  • 1
    Just to be clear... we're talking about _simulating_ an Alt+Click via JavaScript? – Ashley Strout Jun 19 '12 at 06:45
  • If you mean to detect when someone alt-clicked an element: What's wrong with just detecting a click and checking if the ALT key is pressed? – Benjamin Gruenbaum Jun 19 '12 at 07:08
  • See the answer (esp. the [`initMouseEvent`](https://developer.mozilla.org/en/Document_Object_Model_(DOM)/event.initMouseEvent) call) in the answer for http://stackoverflow.com/questions/6157929/how-to-simulate-mouse-click-using-javascript (...possible duplicate?). – apsillers Jun 19 '12 at 07:15

2 Answers2

2

This can be done in vanilla JS using initMouseEvent:

event.initMouseEvent(type, canBubble, cancelable, view, 
                     detail, screenX, screenY, clientX, clientY, 
                     ctrlKey, altKey, shiftKey, metaKey, 
                     button, relatedTarget);

As you can see, arguments ten through thirteen apply modifier keys to a programmatically triggered mouse event. The MDN page linked above has a small example on how to use initMouseEvent practically:

function simulateClick() {
    // create a new mouse event
    var evt = document.createEvent("MouseEvents");

    // initialize all the parameters of the event
    evt.initMouseEvent("click", true, true, window,
      0, 0, 0, 0, 0,
      false, false, false, false,  // ctrl, alt, shift, meta
      0, null);

    var cb = document.getElementById("checkbox");

    // actually fire the event on the `cb` element
    var canceled = !cb.dispatchEvent(evt);

    // if the event was cancelled...
    if(canceled) {
        //...
    }
}

Note that older IE versions only support initEvent, which does not seem to allow modifier key options.

apsillers
  • 112,806
  • 17
  • 235
  • 239
1

You can trigger an event manually. for your case - you can try to trigger a keydown event and a click event.

this is how you can trigger an event with jQuery:

var e = jQuery.Event("keydown");
e.which = 9; // # Some key code value - in your case tab
$("input").trigger(e);

this is how you trigger click:

$("#target").click();

JsFiddle: http://jsfiddle.net/sagivo/Bdtpj/

Sagiv Ofek
  • 25,190
  • 8
  • 60
  • 55
  • But as I understand it, this is a _hypothetical_ situation where the asker doesn't necessarily control all the code being run, and may still want to simulate an Alt+Click. – Ashley Strout Jun 19 '12 at 06:50