ofer dofer
ofer dofer

Reputation: 621

JS: Applying focus effect on an element when scrolled to

Here is the fiddle: http://jsfiddle.net/fz5Yk/5/

All I want to achieve is to highlight (e.g adding a background color) the heading (in <strong> </strong> tag) of the section-3 when I scroll to section-3.

I'd like to know if there's a way for me to trigger certain events when I'm at a certain section. There must be a thing for this because when you scroll the page manually, you'll notice that, in the navigation menu, link to the section gets selected automatically, as if it was clicked.

Anything helpful will be much appreciated as I've been working on this since yesterday and hav yet to solve it.

Upvotes: 1

Views: 370

Answers (3)

Jay Na
Jay Na

Reputation: 837

There isn't any way to achieve this using CSS, so I edited the jquery.nav.min.js. (added only 4 lines) It works great now. http://jsfiddle.net/fz5Yk/10/

adjustNav=function(a,b,d){
                var sec = a.find("."+d+">a").attr("href");
                $(sec+">strong").css('background','none'); //Find and remove previous highlight of strong  
                a.find("."+d).removeClass(d);b.addClass(d); //ORIGINAL

                sec = b.find("a").attr("href");
                $(sec+">strong").css('background','aqua'); //Find and highlight the strong
};


EDIT: Animation added by request: http://jsfiddle.net/fz5Yk/11/

add animateSomething function on top:

function animateSomething(sec) {
    if(sec == "#section-2")
        $("#testBlock").animate({
            width:"50%",
            opacity:0.5
        }, 1500);
}

add animateSomething(sec); at the end of adjustNav function.
Voila!

EDIT FINAL: Animate AFTER scroll ends http://jsfiddle.net/fz5Yk/12/

Upvotes: 1

Andy
Andy

Reputation: 30135

Not sure if that's what you want exactly, but you could use this to add a class to the every strong which is currently in view:

$(document).scroll(function(){
    var t = $(this).scrollTop();
    var b = t + $(this).height();
    $('.section>strong').removeClass('highlight').filter(function(){
        var ot = $(this).position().top;
        return ot > t && ot < b;
    }).addClass('highlight');
});

http://jsfiddle.net/fz5Yk/7/

But it is a bit pointless in my opinion because when it's not in view why do you want to remove the highlight? It won't be visible anyway!?

If you really only want the functionality for section 3 you could change $('.section>strong') to $('#section-3>strong')

Upvotes: 0

AmbrosiaDevelopments
AmbrosiaDevelopments

Reputation: 2592

In your click action have something like this:

$("#container .section strong").css('background-color', 'transparent');
$("#container .section strong:contains('" + $(this).text() + "')").css('background-color', 'yellow');

Upvotes: 0

Related Questions