javascriptjqueryhtmlonmouseoverjquery-hover

JavaScript or JQuery to make an element behave like a link - onmouseover or hover?


Well, this time I have a rather sticky problem: make a TR row of a HTML table behave like a hyperlink. :/ Unfortunately I can't change the basic structure of HTML to use DIVs (due to coding requirements - it's a long story).

So what's the problem?

Basically, I know that the onclick (JavaScript) or click (JQuery) will link these elements up to the pages I need, and I have implemented these solutions with success. However, I would like them to act like hyperlinks while the user is hovering, so that the user sees (via the "hand" or whatever hover icon in his browser) that he is looking at a link, and can right-click and open in a new window.

I know that I can use onmouseover and hover methods for respectively JavaScript and JQuery. The problem is, I haven't the faintest idea what code to put in such methods to make them work the way I need, and my search on Google has been thus far fairly fruitless. :/

My working code thus far

With HTML and JavaScript

My HTML:

<tr class = "oneResultat" onclick="DoNav('annonce.php')">
    ...
</tr>

And JavaScript:

function DoNav(url)
{
    document.location.href = url;
}

With HTML and JQuery

My HTML:

<tr class = "oneResultat" href = "annonce.php">
    ...
</tr>

My JQuery:

jQuery(document).ready(function($) {
    $(".oneResultat").click(function() {
        window.document.location = $(this).attr("href");
    });
});

Solution

  • The only way to get default anchor handling in the browser - is to use anchors! But since you can't wrap the TR in an anchor, you must wrap the contents of each TD in an anchor. This will work best if your TD's are rendered without gaps between them.

    HTML:

    <tr class="oneResultat" data-href="annonce.php"> ... </tr>
    

    Javascript:

    jQuery(document).ready(function($) {
      var $oneTR = $(".oneResultat");
      var href = $oneTR.attr("href");
      var wrap = "<a href='"+href+"'></a>";
      $("tr.oneResultat > td").wrapInner(wrap);
    });
    

    Possible CSS to make the anchors display full-width in the TD's:

    tr.oneResultat > td > a {
      display:block;
      width:100%;
      height:100%;
    }
    

    Note this creates regular anchors which are triggered by left-click, not right-click. If you must use right-click, then make the anchors href='#' and attach an event handler for click on those anchors, then invoke one of the many jQuery contextmenu plugins to render a context-sensitive menu. Let me know if you want an example of that, but for now I'll assume you want regular left-click browser anchor behaviour.