codeandcloud
codeandcloud

Reputation: 55200

Underline a Hyperlink On Hover using jQuery

I used the method

$("#dvTheatres a").hover(function (){
        $(this).css("text-decoration", "underline");
    },function(){
        $(this).css("text-decoration", "none");
    }
);

Is there a more elegant method?(single line)

Upvotes: 10

Views: 19544

Answers (4)

Rick
Rick

Reputation: 13490

Give this a try

$('.my-awesome div a').hover().css('text-decoration', 'none');

Upvotes: 0

nickf
nickf

Reputation: 546025

You might be having issues with other CSS rules overriding the one you want. Even if it is declared last in the file, other declarations might have more importance and hence your will be ignored. eg:

#myDiv .myClass a {
    color: red;
}
#myDiv a {
    color: blue;
}

Because the first rule is more specific it takes precedence. Here's a page explaining CSS Specificity: http://www.htmldog.com/guides/cssadvanced/specificity/

The reason your jQuery solution works is because applying a style via the style="" parameter has very high specificity.

The best way to find which rules are being applied and which are being overruled by others is to use the Firebug extension for Firefox. Inspect the element in that and click on the CSS tab: it will show you every single CSS declaration which is being applied, and put a strike-through on ones which are being overruled.

If you want a really quick and easy way to solve your problem though, try this:

#dvTheatres a:hover {
    text-decoration: underline !important;
}

if you really want to stick to using jQuery, your method is fine and probably the most elegant way to do it (using jQuery).

Upvotes: 13

Reputation:

No good answer, but maybe you're just looking for alternatives. One is to use named function (and CSS) instead to express intent rather than in-lining raw instructions.

Script

function toggleUnderline() { $(this).toggleClass('underline') };
$("#dvTheatres a").hover(toggleUnderline, toggleUnderline);

CSS

.underline { text-decoration: underline; }

Upvotes: 1

Paige Ruten
Paige Ruten

Reputation: 176645

Why not just use CSS?

#dvTheatres a {
    text-decoration: none;
}

#dvTheatres a:hover {
    text-decoration: underline;
}

Upvotes: 14

Related Questions