0

Possible Duplicate:
How can I capture the right-click event in JavaScript?

I have links that, when clicked, execute some javascript code. Just like this:

<script>
        function myFunction(){
            alert("Hello World!");
        }
</script>

<a href="http://google.com" onclick="myFunction()">Click</a>

When I do "Right click -> Open in a new tab" it directs me to 'google.com' without calling myFunction(). And that's exactly what I want.

The problem shows up when I open the link in new tab by pressing the link "Ctrl+Left click". This way, it executes myFunction() and then goes to google.com.

Is there any way to fix this?

Community
  • 1
  • 1
aur0n
  • 463
  • 3
  • 14
  • 25
  • 1
    onclick events should include the keypress data as part of the event handler. you'd simply mod myFunction to check if ctrl was down when the click occurs and bypass the rest of the function if so – Marc B Oct 05 '12 at 14:39

1 Answers1

3

Check in myFunction to see whether or not a modifier key is pressed.

function myFunction(e) {
    // http://www.quirksmode.org/js/events_access.html
    var event = e || window.event;

    // https://developer.mozilla.org/en-US/docs/DOM/MouseEvent
    if (event.ctrlKey || event.metaKey) return;

    alert("Hello World!");
}

N.B. this exact code may not work in all browsers (that's what JavaScript libraries are for).

http://jsfiddle.net/mattball/vEHyj

Matt Ball
  • 354,903
  • 100
  • 647
  • 710