H.Marxen
H.Marxen

Reputation: 33

jquery .hover() confusion

I am currently programming my portfolio page and I came across a strange behaviour off hover states that I don't understand. I have some links in a navigation bar at the top of my page. The links are fully defined with :hover and everything. Now I also want the colour of the links to change when I hover the mouse over the different sections of the site that the links refer to. So I wrote this:

/* Navlink colors */
$('#portfolio').hover(function() {
       $('#portLink').css('color','#FF9900');
    }, function() {
       $('#portLink').css('color','inherit');
});
$('#about').hover(function() {
       $('#aboLink').css('color','#FF9900');
    }, function() {
       $('#aboLink').css('color','inherit');
});
...

At first it seems to work, but when you scroll to the blog and then move the mouse over the navigation the css :hover doesn’t seem to work anymore. This is my test site:

http://www.henning-marxen.de/test/index.html (Don't laugh those are placeholders^^) Do you know why it behaves like this? I am very confused. Thank you very much in advance.

Upvotes: 0

Views: 94

Answers (3)

Ryan
Ryan

Reputation: 3926

You need a mix of js and css for this. In your css you need to apply your styles with the hover state but also with a class which I'll call current for this example.

.nav-link:hover,
.nav-link.current{
  color:#FF9900;
}

Then all you javascript needs to do is add or remove the class depending on which part of the site you have scrolled to:

var navLinks = $('.nav-link');

//each time the user scrolls, reset all links by removing class.
navLinks.removeClass('current');

//Then find the link that needs highlighting and add the class to it.
//There obviously needs to be some logic here to filter the correct link.
navLinks.filter('[href="#portfolio"]').addClass('current');

Upvotes: 0

Stuart Kershaw
Stuart Kershaw

Reputation: 17671

You should use CSS for this, not jQuery:

#portLink:hover, #about:hover { color: #FF9900; }

Or (to more explicitly match your JS):

#portfolio:hover #portLink, #about:hover #aboLink { color: #FF9900; }

If your link elements are not descendent of those first selectors, use + to group them (as indicated in this fiddle): http://jsfiddle.net/B8Xuw/ *note this assumes they are siblings rather than parent>child

#portfolio:hover + #portLink, #about:hover + #aboLink { color: #FF9900; }

Upvotes: 1

Charlie
Charlie

Reputation: 1293

Try this:

 /* Navlink colors */
    $('#portfolio').hover(function() {
       $('[href="#portfolio"]').css('color','#FF9900');
    }, function() {
       $('[href="#portfolio"]').css('color','inherit');
    });
    $('#about').hover(function() {
       $('[href="#about"]').css('color','#FF9900');
    }, function() {
       $('[href="#about"]').css('color','inherit');
    });

Upvotes: 0

Related Questions