2

I have something like:

<tr><td><a href="...">text</a></td>...</tr>

I need to enable user to click on entire table row to navigate on that link.

Now I use the following code:

$(function () {
    $('tr').each(function () {
        var tr = $(this);
        if (tr.hasClass('no-row-link')) return;
        var links = $('a', tr);
        if (links.length != 1) return;
        tr.addClass('row-link').click(rowLinkClick);
    });

    function rowLinkClick() {
        var tr = $(this);
        var links = $('a', tr);
        if (links.length != 1) return;
        window.location = links.attr('href');
    }
});

but the problem is, this behaviour is not working very nice. User can command-click on normal link to open page in new tab, but he can't here. User can right-click on normal link to view link context menu, but he can't here.

The only way I can do what I want is to iterate throw table cells (th/td) and wrap their contents on links. And then make those links behave with display:block. This isn't very elegant solution. Is there any other solutions for that?

vbezhenar
  • 11,148
  • 9
  • 49
  • 63

2 Answers2

1

How about using a data-attribute on your rows?

<tr data-href="yourlinkhere"><!--whatever comes here--></tr>

Then in jQuery:

$('.table-selector').on('click', 'tr', function(){
    var href = $(this).data('href');

    if (href){
        window.location = href;
    }
});

It certainly looks more elegant, don't you think? ^^

UPDATE: Ah, the right click behavior ... kk

tr { position: relative; }
tr a { position: absolute; display: block; width: 100%; height: 30px/*or something*/ }

CSS solution, not sure about the flexibility of your table but if possible ... here's a DEMO of how I would try it.

Tim Vermaelen
  • 6,869
  • 1
  • 25
  • 39
-1

You can check the e.ctrlKey property and either use window.navigate or window.open accordingly:

$(function () {
    function rowLinkClick(e) {
        var href = $(this).find('a').attr('href');
        if (href) {
            (e.ctrlKey ? window.open : window.navigate)(href);
        }
    }

    $('tr')
        .not('.no-row-link')
        .has('a')
        .addClass('row-link')
        .click(rowLinkClick);
});

And you can use CSS to show a link-like mouse cursor:

.row-link {
    cursor: pointer;
}

http://jsfiddle.net/zmr6whjh/2/

I think having a right-click on the row show the context menu for the link might be a bit much. I'm not sure there's a sensible way to do that.

JLRishe
  • 99,490
  • 19
  • 131
  • 169