JSFiddle - React, Tailwind, and code Playground
HTML
<div>
<button id="cheat-button">Fake Click, and Suppress Handler</button>
</div>
<div>
<button id="mimic-button">Follow Link without Clicking</button>
</div>
<a id="example-link"
href="https://www.google.com/"
target="_blank"
onclick="window.open('https://www.google.com/', '', 'width=50, height=50');">
<span>Middle Click Me</span>
</a>
CSS
div{ margin: 1em; }
button{ padding: 0.3em; border-radius: 0.5em; }
span{ margin: 1.3em; }
JavaScript
const
// Identifies some DOM elements
cheatButton = document.getElementById("cheat-button"),
mimicButton = document.getElementById("mimic-button"),
exampleLink = document.getElementById("example-link"),
// Defines an event to be dispatched programmatically
middleClick = new MouseEvent("click", {button: 1, which: 2});
// Demonstrates calling the functions
cheatButton.addEventListener("click", emulateMiddleClick); // Option 1
mimicButton.addEventListener("click", followLink); // Option 2
// Defines the functions
function emulateMiddleClick(){
const onclickHandler = exampleLink.onclick; // Remembers onclick handler
exampleLink.onclick = ""; // Supresses onclick handler
exampleLink.dispatchEvent(middleClick); // Dispatches middle click
exampleLink.onclick = onclickHandler; // Restores onclick handler
}
function followLink(){
if(!exampleLink.href){ return; } // In case href attribute is not set
const {href, target} = exampleLink; // Gets props by using "destructuring"
window.open(href, (target || "_blank")); // In case target attribute is not set
}