Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

prevent link click event except open in new window hotkey is pressed

So I have my website, a website without reload between site switches.
For SEO reasons, my links look like this:

<a href="/site2" id="viewmore">View more</a>
<script>
// code is strongly simplified, for more clarity
document.getElementById("viewmore").addEventListener("click",function(e) {
   e.preventDefault();
   myHandler.goTo(e.currentTarget.href);
});
</script>

myHandler is the site handler in this case.

If I click the hotkey for opening a link in a new tab (on Mac it is CMD+Click), it does not work, as the event is prevented.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How to check if the link should open in a new tab or not? (Check if the hotkey is pressed or not)

>Solution :

Not sure I understood it, but try this

document.getElementById("viewmore").addEventListener("click", (e) => {
 // ctrlKey / altKey / shiftKey
 if (e.ctrlKey) myHandler.goTo(e.currentTarget.href);
 else e.preventDefault();
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading