2

I created a very small script that creates an alert box saying "YOU CLICKED!" every time a person left clicks on the page, my problem is that i wish for it to occur upon right click too (this is for demonstration/experimentation purposes only). Here is my original script:

<script>
window.onclick=function() {alert("You clicked!");}
</script>
1
  • You should mark @pimvdb's answer as accepted Commented Nov 14, 2016 at 10:44

3 Answers 3

11

Use oncontextmenu:

window.oncontextmenu = function() {
    alert(':)');
    return false; /* prevent context menu from popping up */
};
Sign up to request clarification or add additional context in comments.

2 Comments

@Blake Myers: Not trying to be pressing you into anything, but if this was the answer could you please accept it bij clicking the tick on the left :)
I don't think we'll hear from @BlakeMyers again, and I can't mark your answer as accepted, so I upvoted it instead
0
<script>
window.onclick=doSomething(e);
function doSomething(e) {
    var rightclick;
    if (!e) var e = window.event;
    if (e.which) rightclick = (e.which == 3);
    else if (e.button) rightclick = (e.button == 2);
    alert('Rightclick: ' + rightclick); // true or false
}
</script>

Does this work?

2 Comments

This brought the same result of an alert on left click only, I needed to use window.oncontextmenu, but thank you for your response.
The click event is "by definition" a left mouse click so the onclick event is only for left click. If you want to capture right click, you have to either generically capture mousedown and then check the event to see if it's the right button or capture the contextmenu event.
0

G'day @Blake-Myers,
Found this by searching the site.

Have you tried adding this property to body or element?
Note: The 'return false' is really important.

oncontextmenu="javascript:alert('success!');return false;"

Then add this script so it applies to the entire page:

var onMousedown = function (e) {
     if (e.which === 1) {/* Left Mouse Click */}
     else if (e.which === 2) {/* Middle Mouse Click */}
     else if (e.which === 3) {/* Right Mouse Click */}
};
clickArea.addEventListener("mousedown", onMousedown);

Cheers mate!

Comments

Your Answer

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.