Using a div, I created a menu that must appear when the user right-clicks the first row of a table:
HTML
<table>
<tr onMouseDown='showMenu(event)' onContextMenu='return false'>
<td>First row</td>
</tr>
<tr>
<td>Second row</td>
</tr>
</table>
<div id='divMnuTable' style='display:none' class='mnuTable'>Menu</div>
Javascript
function showMenu(e) {
e = e || window.event;
// get mouse coordinates
var docEl = document.documentElement;
var scrollLeft = docEl.scrollLeft || document.body.scrollLeft;
var scrollTop = docEl.scrollTop || document.body.scrollTop;
var x = e.pageX || (e.clientX + scrollLeft);
var y = e.pageY || (e.clientY + scrollTop);
// show the menu
var div = document.getElementById('divMnuTable');
div.style.left = x+'px';
div.style.top = y+'px';
div.style.display = 'block';
}
CSS
table {
border: 1px solid black;
}
tr:nth-child(odd) {
background-color: #CCFFCC;
}
.mnuTable {
background-color: #90A090;
position:absolute;
}
JSFiddle: https://jsfiddle.net/q5brjfyw/
I can't reproduce the error in the fiddle above, but it happens on my Firefox/Ubuntu. (In the fiddle, the console says "showMenu is not defined" -- is this usual behavior for javascript in jsfiddle.net? Because the function is there on the Javascript panel!).
What is happening is: without this line
div.style.display = 'block';
Firefox's context menu don't show up. That's what I want, and I get it because of the onContextMenu='return false'
. But when I add
div.style.display = 'block';
it shows both, my div-menu and Firefox context menu! Why is that? I've tried other commands to hide the context menu, but it keeps showing. I tried all of the below, isolated and mixed:
e.preventDefault();
if (event.stopPropagation)
event.stopPropagation();
event.cancelBubble = true;
return false;
So, how do I hide the default context menu to show my own menu instead?