EDDYMENS

Last updated 2024-03-04 20:32:40

Enabling A Tag Click Event To Open A Page In A New Tab With Ctrl Or Command Key Press

Table of contents

Introduction

When you intercept a click on an A tag using the onclick event and override the default behavior using event.preventDefault();, it's now up to you to define its new behavior.

Let's say you want to load a locally cached version of the requested page. A problem arises when the user combines the link click with the Ctrl or Command key.

In such cases, to open up the page in a new tab, you don't want to serve the user with the cached page in the current tab. Instead, you might want to revert to the default behavior of opening the page in a new tab.

Detecting control or command key combo

Here is the code to detect when the A tag is clicked with either the Ctrl or command key pressed down.

Ctrl was pressed

01: anchor.addEventListener('click', function (event) { 02: if (event.ctrlKey || event.metaKey) { 03: return; 04: } 05: event.preventDefault(); 06: // Your code here 07: });

You might also want to check if the tag has target set to blank.

Check if target is set

01: anchor.addEventListener('click', function (event) { 02: if (event.ctrlKey || event.metaKey || this.getAttribute('target')) { 03: return; 04: } 05: event.preventDefault(); 06: // Your code here 07: });

Ideally, you should check for this before setting the onclick event.

Detecting mouse middle button key press

Some mice open a page when clicking the middle button. This can be handled by checking if the middle button is pressed using the event.button.

The click event will only be triggered if the mouse is mapped to open a page when clicked.

Check if middle mouse button is pressed

01: anchor.addEventListener('click', function (event) { 02: if (event.ctrlKey || event.metaKey || this.getAttribute('target') || event.button === 1) { 03: return; 04: } 05: event.preventDefault(); 06: // Your code here 07: });

Detecting shift key press

Similar to the middle mouse button, pressing down on the Shift key and then clicking on an A tag can cause the page to open.

Check if shift is pressed

01: anchor.addEventListener('click', function (event) { 02: if (event.ctrlKey || event.metaKey || this.getAttribute('target') || event.shiftKey || event.button === 1) { 03: return; 04: } 05: event.preventDefault(); 06: // Your code here 07: });

Putting it all together

Alright, let's put everything together.

Complete code

01: anchor.addEventListener('click', function (event) { 02: if (event.ctrlKey || event.metaKey || this.getAttribute('target') || event.shiftKey || event.button === 1) { 03: return; 04: } 05: event.preventDefault(); 06: // Your code here 07: });

It's important to note that this is more of a "whitelisting" approach, meaning a user might have some kind of key mapping that we are unaware of.

Here is another article you might like 😊 "Diary Of Insights: A Documentation Of My Discoveries"