Autify JavaScript Snippets
Toggle Dark/Light/Auto modeToggle Dark/Light/Auto modeToggle Dark/Light/Auto mode Back to homepage

Right click

Use this snippet to fire a right-click event on an element.

Change the following value to specify the element:

  • selector: A string of the element selector
/* Specify the element selector */
var selector = "<TODO: REPLACE SELECTOR>";

/* --------- You don't need to touch below --------------- */

/* Locate the element */
var element = document.querySelector(selector);

/* Exit if it does not exist */
if (!element) {
  throw new Error(
    "Error: cannot find the element with selector(" + selector + ")."
  );
}

/* Create and init a right-click (to be exact, contextmenu) event */
var event;
if (typeof Event === "function") {
  /**
   * For modern browser
   */
  event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });
} else {
  /**
   * For IE 11
   */
  event = document.createEvent("MouseEvents");
  event.initEvent("contextmenu", true, true);
}
/* Fire a right-click event */
element.dispatchEvent(event);