I am trying to create a custom context menu for my website. I have been unable to accomplish the first task, which would be capturing and preventing the default of a right click. I have tried the following:
function rclick(event) {
if (event==null) {event = window.event;}
var target = event.target != null ? event.target : event.srcElement;
console.log(event.button);
if ((event.button == 2 || event.button==4 || (event.keyCode==17 && event.button ==0)) && target.tagName.toLowerCase() == 'a') {//1 and not internet explorer - middle
event.preventDefault();
var scrollTop = document.body.scrollTop ? document.body.scrollTop :
document.documentElement.scrollTop;
var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft :
document.documentElement.scrollLeft;
document.getElementById("context").style.left = event.clientX + scrollLeft +'px';
document.getElementById("context").style.top = event.clientY + scrollTop +'px';
document.getElementById("context").style.display = 'block';
}
}
I have attached the event to all anchor elements with:
$(document).ready(function(){$("a").bind("click",function() {rclick(event);});});
When I left-click on an a element, event.button gives me '0'. But when I right click, the browser context menu appears, and the event does not fire (the value will not appear in the console log. How can I capture the right click and prevent default?
----update----
I have added this line:
$(document).ready(function(){$('a').on("contextmenu", function(evt) {evt.preventDefault();});});
and that successfully prevented the context menu from appearing on right click on anchor elements. However, when I add these lines to my mousedown function:
document.getElementById("conmen").style.left = event.clientX + scrollLeft +'px';
document.getElementById("conmen").style.top = event.clientY + scrollTop +'px';
document.getElementById("conmen").style.display = 'block';
then the context menu appears on top of the custom context menu I have designed. Why would these lines make the browser context menu appear?