JavaScript implementation press Ctrl to open a new page

  • 2020-03-30 03:52:00
  • OfStack

This article addresses the problem of using JS to open a new page when you press Ctrl.

In the simplified HTML5 specification, multiple divs and/or other block-level elements are allowed within the A tag. A> The tag wraps around the block element, and you can see that you need JavaScript to listen and call window.location to redirect the page.

But using < A> This wrapper form of a label also has its drawbacks -- for example, there are a few more inside a block element. A> Tag, in which case we just want to click on parent < A> Does not jump to a given address until it is part of something else.

Of course, a simple listener like the following can also fulfill our requirements:


someElement.addEventListener('click', function(e) {
    //The URL can be anything, or you can specify it using some other code     //The 'data-src' DOM attribute of the element is used here
    window.location = someElement.get('data-url');
});

... But this can sometimes be a terrible user experience. When you hold down the CTRL key (Mac is COMMAND) and then click with the mouse, it opens the link in the same window. Knowing that there is a problem, you must have thought of how to solve it. We can modify a little bit of code to achieve this purpose, so please spend some time to repair your listener.


someElement.addEventListener('click', function(e) {
    //Get the URL < br / >     var url = someElement.get('data-url');
    //Determines if the CTRL key is pressed
    if(e.metaKey || e.ctrlKey || e.button === 1) {
        window.open(url);
    } else {
        window.location = url;
    }
});

The author has already implemented this feature at http://davidwalsh.name/, and you should remember this when using window.location for page redirection. This is a small code improvement, but very important for usability!


Related articles: