JAVASCRIPT: Custom right-click menu
Many of you may have already noticed that there is no text link to my Admin panel. That is because it is cleverly hidden. If you right click anywhere on this page in most modern browsers, you will be greeted by my admin logon in your cursors location
.
You could use this for whatever purpose you want, here I will just show you how I did it personally.
Firstly, the code for the "hidden" menu is always loaded with every page in this website. It sits inside a little div tag which is hidden with css.
Here is how this div should look when I remove all my content::
[code]
<div id="adminpop" style="display:none">
<div onclick="this.parentNode.style.display='none'">x</div>
</div>
[/code]
The declaration [i]style="display:none"[/i] ensures that everything inside the div is hidden from view when the page is rendered. The next div is shows an X in the hidden window which when clicked will hide it again.
[b]Now for the Javascript[/b]
[code]
document.oncontextmenu=function(ev)
{
var ev=ev || window.event;
var pop=document.getElementById('adminpop');
var x,y
if (document.all) //IE Workaround
{
if(ev.srcElement.tagName.toLowerCase()=="input" || ev.srcElement.tagName.toLowerCase()=="textarea")
return;
x=ev.clientX + document.body.scrollLeft;
y=ev.clientY + document.body.scrollTop;
}
else
{
if(ev.target.tagName.toLowerCase()=="input" || ev.target.tagName.toLowerCase()=="textarea")
return;
x=ev.pageX;
y=ev.pageY;
}
pop.style.left=x+"px";
pop.style.top=y+"px";
pop.style.display="block";
return false;
};
[/code]
This code should be pretty self-explanatory but I will now explain it bit by bit.
The first line defines our function to be called everytime the "context menu" is opened (This is the right-click menu). After this we define our variables, the one that concerns us most is [b]pop[/b] which must have the same ID set as your hidden div. [b]ev[/b] is used to capture the mouse location and [b]x + y[/b] will be used to store the information.
There is an if conditional which is used for cross-browser compatibility. They both contain code that gets and sets the X and Y coordinates of the mouse cursor when the right mouse button is clicked. They also both contain the following:
[code]
if(ev.srcElement.tagName.toLowerCase()=="input" || ev.srcElement.tagName.toLowerCase()=="textarea")
return;
[/code]
This is optional and allows the right-click menu to still appear as normal on form elements that require typing. I did this to allow selection and copy-pasting to occur as normal.
After this the last 4 lines set the coordinates, set the display CSS property to "block" and then [i]return:false[/i] to cancel the standard right click menu.
I hope this was a useful tutorial. Please ask away in the comments if you have any problems.
Thanks
Stephen