I have an unordered list of links that act as filters for content below.

Link 1 Link 2 Link 3 Link 4

On click of any link, the class "active" is added to the link clicked. This works perfectly as it is.

Link 1 Link 2 Link 3 (active) Link 4

But once I scroll down the page, that link goes out of view, so I want the "active" link to stick to the top by adding another class "fixednav".

Link 3 (active) + (on scroll I want this active link to stick to the top)

**I basically need to combine these two with the active-click fiddle being first:

http://jsfiddle.net/m35dB/1/

http://jsfiddle.net/zq9hd/**

How would I write this?

I get a "Uncaught TypeError: Cannot read property 'top' of undefined" for the "active" class. It doesn't exist yet because I haven't clicked any of the filters.

Filter code:

$('#filters a').click(function(){

    if( $(this).is('.active') ) {
       // don't do anything while class is active
    }
    else {
        $('#filters a').removeClass('active'),
        $(this).addClass('active');
    }

});

Scroll code:

function fixDiv() {
    var $div = $(".active");
    if ($(window).scrollTop() > $div.data("top")) { 
        $('.active').addClass('fixednav'); 
    }
    else {
        $('.active').removeClass('fixednav');
    }
}

$(".active").data("top", $(".active").offset().top);
$(window).scroll(fixDiv);
有帮助吗?

解决方案

Try moving $(".active").data("top", $(".active").offset().top); to inside your click function like this:

$('#filters a').click(function(){
    var $this = $(this);
    if(!$this.is('.active'))
    {
        $('#filters a').removeClass('active').removeData("top");
        $this.addClass('active').data("top", $this.offset().top);
    }
});

其他提示

Well, $('.active') returns a set of elements, not a single element.

Try use something like $('.active:first').

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top