(Translator's note: This article solves the problem of using JS to open a new page when pressing the Ctrl key)
In the simplified HTML5 specification, multiple DIVs and/or other block-level elements are allowed to be included in the A tag. Now, just wrap the block elements with the <a> tag, you can solve the problem that you originally needed to listen with JavaScript and call window.location to achieve the page redirect function.
However, this wrapping form using the <a> tag is also not working well - for example, there are some <a> tags in a block element. In this case, we only want to jump to a given address when clicking on other parts other than <a> in the parent.
Of course, using a simple listener like the following can also achieve our needs:
The code copy is as follows:
someElement.addEventListener('click', function(e) {
// Any URL address is OK, or you can use other code to specify it.
// Here is the `data-src` DOM attribute of this element (attribute)
window.location = someElement.get('data-url');
});
...But this sometimes has a bad user experience. When you hold down the CTRL key (Mac is the COMMAND key) and click with the mouse, it will open the link in the same (tab) window. Knowing that there is this problem, you must have thought of how to solve it. We can achieve this by modifying a little code. Take some time to fix your listener:
The code copy is as follows:
someElement.addEventListener('click', function(e) {
// Get URL
var url = someElement.get('data-url');
// Determine whether the CTRL key has been pressed
if(e.metaKey || e.ctrlKey || e.button === 1) {
window.open(url);
} else {
window.location = url;
}
});
The original author has implemented this function on the http://davidwalsh.name/ website, and you should remember this when using window.location for page redirection. This is a small code improvement, but it is very important to improve usability!