Skip to content

Disabling context menu on chart

Normally, browsers will display a context menu when you press right mouse button over some element. If done over amCharts 5, it will display a context menu for a <canvas> element. This tutorial will show how you can disable default behavior of a right-click on canvas elements, as well as attach built-in rightclick event to apply your own logic.

To disable default context menu, we’ll need to cancel contextmenu event, on the <div> root element is placed in:

root.dom.addEventListener("contextmenu", function(ev) {
ev.preventDefault();
});

Or we can use amCharts 5’ built-in utility, which returns a Disposer:

am5.utils.addEventListener(root.dom, "contextmenu", function(ev) {
ev.preventDefault();
});

And to be completely on the safe side, we can add that disposer to root element disposer list, so when root element is disposed, the event handler goes with it:

root.addDisposer(
am5.utils.addEventListener(root.dom, "contextmenu", function(ev) {
ev.preventDefault();
})
);

With built-in context menu out of the way, we can add amCharts rightclick event on the target elements.

The following code adds one to Force-directed tree nodes:

series.nodes.template.events.on("rightclick", function(ev) {
console.log("Right click")
});
Open in CodePen