Click Entire Row (preserving middle click and ctrl+click)
Asked Answered
F

10

35

I have an HTML table with a link in the first column. I want to allow the user to click anywhere in the row to activate that link. At the same time, I would like to preserve the middle click and ctrl+click functionality of opening a new tab/window. Here is an example of the table:

<table id="row_link"> 
  <tbody> 
    <tr>
      <td><a href="link1.html">link</a></td> 
      <td>info 1</td> 
    </tr>       
    <tr>
      <td><a href="link2.html">link</a></td> 
      <td>info 2</td> 
    </tr>       
  </tbody> 
</table> 

Using jQuery I can allow the user to left click anywhere in a row:

$("table#row_link tbody tr").click(function () {
    window.location = $(this).find("a:first").attr("href");
});

This of course disables the standard middle click and ctrl+click functionality of opening a new tab. Is there a better way to allow users to click on the entire row while preserving the standard middle click and ctrl+clcik behavior?

Fibrous answered 20/5, 2009 at 23:32 Comment(0)
B
35

Unfortunately there is no way to simulate a link and all associated behaviour in every browser. Therefore, the only way to achieve what you want is to have a link that follows the cursor around the <tr> element; this link would be invisible so, to the user, it looks like they're clicking on the <tr> but they're actually clicking on a hidden link. Using this method, the middle-button, ctrl+click and any other behaviours are left intact!

Here's a DEMO: http://jsbin.com/ufugo

And here's the code:

$("table tr").each(function(){

    var $link = $('a:first', this).clone(true),
        dim = {
            x: [
                $(this).offset().left,
                $(this).offset().left + $(this).outerWidth()
            ],
            y: [
                $(this).offset().top,
                $(this).offset().top + $(this).outerHeight()
            ]
        }

    $link
        .click(function(){
            $(this).blur();
        })
        .css({
            position: 'absolute',
            display: 'none',
            // Opacity:0  means it's invisible
            opacity: 0
        })
        .appendTo('body');

    $(this).mouseover(function(){
        $link.show();
    });

    $(document).mousemove(function(e){
        var y = e.pageY,
            x = e.pageX;
        // Check to see if cursor is outside of <tr>
        // If it is then hide the cloned link (display:none;)
        if (x < dim.x[0] || x > dim.x[1] || y < dim.y[0] || y > dim.y[1]) {  
            return $link.hide();
        }
        $link.css({
            top: e.pageY - 5,
            left: e.pageX - 5
        })
    });

});

EDIT:

I created a jQuery plugin using a slightly better aproach than above: http://james.padolsey.com/javascript/table-rows-as-clickable-anchors/

Butacaine answered 25/5, 2009 at 8:38 Comment(10)
Great plug-in, it really improved the performance of your example code (for larger tables)! I'm having a small problem, on slower computers when I move the mouse rapidly across the table, rows remain highlighted even after the mouse is no longer hovering over the row.Fibrous
I was able to fix this by transferring the tr mouseover events to the $targetLink, similar to what you did for the mouseout events. After that I bound to the tr mouseover event with the $targetLink.show();Fibrous
Great fix Brian! Thanks! I've added it to the plugin.Butacaine
This is pretty smart. And I like the idea, however it's a problem that now you can't select any of the table data. +1 though.Repertory
@Pim, the same is true for regular anchors. It's a shame there's no compromise to be met.Butacaine
@J-P, you can select the row in my solution. Your workaround is good but it is too hacky and there are much simpler solutions.Polygenesis
@Nadia: My understanding was that the goal was to completely simulate a link and all associated browser dependent behavior. Your approach would be my preferred approach to handling the situation, but that's not the question.Mithgarthr
@Karl, what type of behavior my approach doesn't solve? I'm wrapping all cells in links. Instead of a hidden link that follow the mouse in the row. How is that any different in term of behavior?Polygenesis
@Butacaine I had trouble getting the plugin to work with dynamically created elements. Well the link-clicking aspect worked fine, but the mouseover/mouseout add/remove 'active' class was not working correctly. If I hover over a superLink, the 'active' class gets added to the row and removed at the same time, and you never see the row highlight.Curlew
Great plugin, hover seems to work too. I set display:none for the original links.The blog post seems to have a broken link to the code, remove "/view" from the end - james.padolsey.com/demos/plugins/jQuery/superLink/…Scurrile
P
13

EDIT

This is simple problem that has a simple solution. I don't see a need for nasty hacks that might break on some browsers or take processing time. Especially because there is a neat and easy CSS solution.

First here is a demo

Inspired by @Nick solution for a very similar issue, I'm proposing a simple css+jquery solution.

First, here is the mini-plugin I wrote. The plugin will wrap every cells with a link:

jQuery.fn.linker = function(selector) {
    $(this).each(function() {
        var href = $(selector, this).attr('href');
        if (href) {
            var link = $('<a href="' + $(selector, this).attr('href') + '"></a>').css({
                'text-decoration': 'none',
                'display': 'block',
                'padding': '0px',
                'color': $(this).css('color')
            })
            $(this).children()
                   .css('padding', '0')
                   .wrapInner(link);
        }
    });
};

And here is a usage example:

$('table.collection tr').linker('a:first');

And All the CSS you need:

table.collection {
    border-collapse:collapse;
}

It's as simple as that.


You can use the event object to check the mouse click type. This article is discussing a similar issue.

Anyway, here is how to do it:

$("table#row_link tbody tr").click(function () {

    if((!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1)){
        if (!e.ctrlKey) {
            // Left mouse button was clicked without ctrl
            window.location = $(this).find("a:first").attr("href");
        }
    }
});
Polygenesis answered 23/5, 2009 at 22:7 Comment(2)
Thanks for the article reference. This gets me most of the way to where I want. The only issue I have is that in the case of middle mouse or ctrl+click case I open a new window using window.open($(this).find("a:first").attr("href"));, which puts the focus on the new window. I want to keep focus on the current window so users can open several tabs each corresponding to rows in the table. Thanks for you help.Fibrous
Careful with your undefined variables. Since href and link inside the $().each wasn't defined with 'var', they'll be global. So you might get wierd errors with href or link values from a previous iteration.Idoux
C
7

I would attack this from the HTML/css side. This used to be a common problem when most sites did all layout in tables.

First make the contents of all table cells into links. If you don't want them to look like links you can use CSS to remove the underline from the 'non link' cells. But they will be links, which is semantically what you want anyway.

Next you want to make the link expand to fill the entire cell. StackOverflow already knows the answer to this:

td a { display: block; width: 100%; height: 100%; line-height: 100%; }

With a typical table with no spaces between the cells the entire row will be clickable. And since this relies on no tricks or browser specific hacks it should work everywhere.

Chesnut answered 28/5, 2009 at 16:23 Comment(1)
Totally agree; definitely cleaner than all the other options.Brandnew
R
6

You want this:

$('table#row_link tbody tr').mousedown( function(e){
    if(e.ctrlKey || (!$.browser.msie && e.button == 1) || ($.browser.msie && e.button == 4)){
        //middle mouse button or ctrl+click
    } else {
        //normal left click
    }
});

This is tested in FF3.0.10, Chrome 1.0 and IE6. I use the mousedown event because neither firefox or IE passes the middle mouse button click to a .click(fn) event.

Repertory answered 24/5, 2009 at 10:53 Comment(1)
This gets me most of the way to where I want (just a quick note you are missing a closing parentheses at the end of your if statement. The only issue I have is that in the middle mouse or ctrl+click case I open a new window using window.open($(this).find("a:first").attr("href"));, which puts the focus on the new window. I want to keep focus on the current window so users can open several tabs each corresponding to rows in the table. Thanks for you help.Fibrous
C
1

You could grab the event and look at it's event code. But there is no real way to know what a browser's behavior for those events.

Circumpolar answered 21/5, 2009 at 0:36 Comment(0)
A
1

Here's something that should work: Instead of using window.location, us .click() to emulate a click on the first inside the element. Also, use a conditional to check for CTRL+Click.

Should look like this:

$("table#row_link tbody tr").click(function (e) {
    if(e.ctrlKey) { 
        // Run Ctl+Click Code Here
    } else { 
        $(this).children('a').eq(0).click(); 
    }
}

Hope this helps!

Dave Romero

Appurtenant answered 23/5, 2009 at 18:58 Comment(0)
R
1

You can make a link and let it floting around in your tr, biding to mouveover event, update href and position

create one pixel link

<table id="row_link">....</table>
<a id="onepixel" style="position:absolute;z-index:1000;width:1px;height:1px;"></a>

update href and position on mouse over

$("#row_link tr").mouseover(
   function(event){
      //update href
      $("#onepixel").attr("href",$(this).find("a:first").attr("href"));
      //update position, just move to current mouse position
      $("#onepixel").css("top",event.pageY).css("left",event.pageX);
   }
);
Raisaraise answered 25/5, 2009 at 10:27 Comment(0)
V
-1

Try putting the a around the td and then apply a display:block CSS element to the td.

That should make the entire area of the td clickable with all buttons as a "normal" link.

An example is probably better:

<table id="row_link"> 
  <tbody> 
    <tr>
      <a href="link1.html"><td style="display: block;">link</td></a> 
      <td>info 1</td> 
    </tr>       
    <tr>
      <a href="link2.html"><td style="display: block;">link</td></a>
      <td>info 2</td> 
    </tr>       
  </tbody> 
</table>

A similar approach has worked in the past for me, although it was not exactly for table elements. Untested with tables so try it.

Vallonia answered 23/5, 2009 at 22:18 Comment(4)
Just realised that perhaps you wanted both TD's to be clickable in the row. My suggestion is only for the specific TD containing the actual anchor. I guess you can still apply the same concept to the TR instead of the TD. Just move the A outside the TR so it "surrounds" it.Vallonia
...obviously applying the display: block to the TR now. instead of the TD.Vallonia
Yes, why not? As written above I have not had the chance to test it, but since the method works for other elements why not give it a try.Vallonia
Semantically it should be correct. I always try to find a pure HTML/CSS solution before taking the easy road with Javascript.Vallonia
N
-1

I think the biggerlink plugin will do what you ask for. Here's the

Nonoccurrence answered 24/5, 2009 at 10:5 Comment(0)
I
-4

you need to remove the < tbody > tag

and just use the 'href' attribute to get the link destination and dont to select the anchor < a > tag too because thats contains the href attribute.

$("table#row_link tbody tr a").click(function () {

     window.location = $(this).attr("href");

});

or simply make the link open a new tab.

i hope that helps you.

Incest answered 21/5, 2009 at 1:10 Comment(1)
Thanks for the idea, however, that only allows users to click on the actual link not anywhere in the row. Also I'm not sure why removing the tbody tag would help.Fibrous

© 2022 - 2024 — McMap. All rights reserved.