Search code examples
jqueryhyperlinkwindowhreflocation-href

Jquery: Make entire block clickable, while preserving the ability to open in a new tab/window


I don't want to use css to expand the link width/height etc.

With my code, the entire LI is clickable, it opens the a link found within it. I've preserved the middle mouse click to open the link in a new window.

  1. I'm wondering if someone who really actually knows what they're doing can guide me in this and let me know if this is the best way to write this, or are there alterations that could be made to my code?

  2. also: can someone help me add a "ctrl+left-click" to open the link in a new window, which is the same thing a middle-mouse-button click does, i'm just not sure how to test for ctrl? I thought changing the else if ((e.which == 2)) { part to else if ((e.which == 2) && (e.which == 16)) { would work, but it doesn't.

code:

$('li a').each(function() {
            $(this).parent().bind('click', function(e) {
                if((e.which == 1)) {
                    alert('left mouse button clicked')
                    window.location=$(this).find("a").attr("href"); return false;
                }
                else if ((e.which == 2)) {
                    alert('middle mouse button clicked')              

                        window.open($(this).find('a').attr('href'));
                        return false;  
                }
            });
        });

Solution

  • Here's your guide for detecting which keys are pressed (it's all through the event coming in): http://www.quirksmode.org/js/keys.html

    Note that on OSX it's impossible in most browsers.