Pure Javascript Context Menu

Hello all,

I’de like to show a context menu when the user right clicks on a anchor element.
The context menu should only show 1 item (delete).
There are many jquery examples on the net but I can’t find a simple JS solution.
Any ideas?


Made simple example for you http://jsfiddle.net/megazd/n6h549f1/

1 Like

Exactly what I was looking for.
Many thanks!

Unfortunately the example only works in later browsers. I have reworked megazoid’s example to allow it to work right back to IE7.

The oncontext menu handler is shown below:

document.getElementById('link').oncontextmenu = function (evt) {
    evt = (evt) ? evt : ((event) ? event : null);
    var posnX = (evt.pageX) ? evt.pageX : ((evt.offsetX) ? evt.offsetX + 10 : null);
    var posnY = (evt.pageY) ? evt.pageY : ((evt.offsetY) ? evt.offsetY + 10 : null);
    menu.style.left = posnX + 'px';
    menu.style.top = posnY + 'px';
    menu.style.display = 'block';
    if (typeof evt.preventDefault != "undefined") {
    } else {
        evt.returnValue = false;

This link is to a working example on JSFiddle.

1 Like

Works like a charm.
Thank you AllanP, I will update my code

It doesn’t seem to work if the anchor element is created dynamically. (Isnt part of the initial HTML)
I’ve got anchor elements that are created with JS. If I try to apply your code on it it does not work. Is there a solution to this?

Do you set oncontextmenu handler after anchor was created?

Your code is set at the bottom of the JS file and is only called after the elements are created.

Can you show how do you create these elements?

I’m not at my computer at the moment. I will try to produce a jsfiddle later on.

Here is the part that creates the elements. Like is said i will provide a jsfiddle later on today

myString = myString + "/<a onclick='replaceElement(this);' id='" + i + "'>" + (uld[i][1]) + "</a>" + (uld[i][2]);

I think the following will suffice as an example


It works if you create links as DOM elements: http://jsfiddle.net/megazd/n6h549f1/5/

Thank you for sharing your knowledge megazoid!
And again you learnt me a lot today.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.