vep temp
vep temp

Reputation: 267

Javascript - addClass() on hover not working

html

<ul class="navBarExtended">
   <li><a href="#">Link</a></li>
</ul>

css

.onHover{
text-decoration: underline;
 }

javascript

$("ul.navBarExtended li a").hover(
    function(){
        $(this).addClass("onHover");
    },
    function(){
        $(this).removeClass("onHover");
 });    

I'm trying to add 'onHover' class on to the element specifically a link, but it seems to be not working..so where you think the problem can be?

Upvotes: 3

Views: 761

Answers (2)

jaypeagi
jaypeagi

Reputation: 3141

A better solution may be to use the :hover pseudo class like so:

ul.navBarExtended li a:hover {
   text-decoration: underline;
}

However, your original code does seem to work (assuming you have set the default CSS for an a element to have no underline): http://jsfiddle.net/jaypeagi/wSG4s/

It's also worth noting that in your code, if you put the script tag before the HTML containing the a elements, it will not work (see here). This is because when the script runs, the elements do not exist. Consider making your code run on the JQuery document ready event. Example here.

Upvotes: 7

Mathew Thompson
Mathew Thompson

Reputation: 56459

I think that's because by default a tags already have that text-decoration. Just add extra css to set it to none by default:

ul.navBarExtended li a {
    text-decoration: none;
}

But you should really just use a CSS class to manage the hover (if possible), by adding:

ul.navBarExtended li a:hover {
    text-decoration: underline;
}

Upvotes: 3

Related Questions