2

I would like to know how I could make a left-click behave as a right-click in javascript. I would like that, by doing a left click, the context menu appears.

Regards.

user2302725
  • 463
  • 6
  • 20

2 Answers2

2
  1. Add a click-event listener to the document
  2. save what element was the lowest in the dom-tree that got clicked
  3. fire an event 'rightclick' (or whatever its called) to that element with the same x and y coords as you have received from the click event.

The event listener:

document.addEventListener('click', function(e) {
    console.log(e);
});

This gives you already a lot of information. You'll get the x/y coords of your mouseclick and more important, you get the element that received the click: e.originalTarget (note that events differ from browser to browser).

save the element:

document.addEventListener('click', function(e) {
    var originalElement = e.srcElement || e.originalTarget;
});

and fire a right-click on that element:

document.addEventListener('click', function(e) {
    var originalElement = e.srcElement || e.originalTarget;
    if (document.createEvent) {
        var ev = document.createEvent('HTMLEvents');
        ev.initEvent('contextmenu', true, false);
        originalElement .dispatchEvent(ev);
    } else { // Internet Explorer
        originalElement .fireEvent('oncontextmenu');
    }
});

edit:

it does not seem to work yet, so consider using this method for firing the right-click in pure js: How to generate a right-click event in all browsers

Community
  • 1
  • 1
Zim84
  • 3,404
  • 2
  • 35
  • 40
0

try this

    $(document).contextmenu(function (event) {
        $(event.target).click();
        event.preventDefault();
    })
sangram parmar
  • 8,462
  • 2
  • 23
  • 47