Reputation: 884
I have a anchor inside a list item
<li>
<a href="page"></a>
<span>description</span>
<span>count</span>
</li>
Using javascript, whenever the list item is clicked, the window opens the anchor's href.
I want to let the browser know that when it middle clicks it can treat the list item the same as the anchor, and open in a new tab.
I've looked around and seen that most people think this cannot be done, but I think my situation could be different. One way of looking at it would be not to explicitly tell the browser to open a new tab, rather tell the browser to do what is does when middle click is used.
What do you think?
EDIT: Updated html for a more accurate description. The anchor is not the only element in the list
Upvotes: 1
Views: 4039
Reputation: 29
_blank wasn't working for me in Chrome V92. Instead - A workaround will be to create a "fake" <a tag that will work only for middle clicks, like this:
<li>
<a href="https://google.com" id="fake-link" >
Only clicks with middle buttons will work
</a>
</li>
<script>
document.getElementById('fake-link').addEventListener("click",(e) => e.preventDefault());
</script>
Upvotes: 0
Reputation: 4924
Using jQuery 1.7
$('ul').on('click', 'li', function(e){
if(e.which == 2){
var newWindow = $(this).find('a').attr('href');
window.open(newWindow, 'newWindow');
e.preventDefault();
}
});
That's it. jQuery normalizes the event.button
to event.which
so you can reliably detect middle clicks. Then just open a new window. Granted, whether or not it ends up in a new tab or a new windows entirely rests on the users' browser preferences.
Upvotes: 0
Reputation: 884
Ok nay sayers :), I've figured out how to do it.
With JS/jQuery I can determine which button is pressed. Using this I can change the target value on the anchor to "_blank" only when the middle button is pressed.
Upvotes: 1
Reputation: 943615
You want the list item to function as a link. The simplest, most reliable way to do this is to get rid of the JavaScript and apply CSS to make the link fill the list item. Then any click on the list item will hit the link first. Listamatic has many examples.
Upvotes: 0