Carl Papworth
Carl Papworth

Reputation: 1322

Change nav a.class on horizontal scroll with jQuery

I'm working with a horizontal design, with a navigation menu in the top left corner. I want each link to change appeareance as you scroll horizontal. I've used the same thing for vertical scroll-navs without any issues. So I tried the same code but using .scrollLeft(); instead of .scrollTop();and .position().left instead of .position().top. Any ideas how to make it work?

Here's a jsfiddle with my code: https://jsfiddle.net/5xx6g7j8/2/

Upvotes: 0

Views: 1008

Answers (2)

GreyRoofPigeon
GreyRoofPigeon

Reputation: 18113

You can remove the visited class from the item, and add it to the active slide (line 6+7):

$(document).ready(function() { 
    //scrollTo
    $('.nextPage, .prevPage').bind('click',function(event){
        var $anchor = $(this);
        // added the next two lines
        $('.nextPage, .prevPage').removeClass('visited');
        $(this).addClass('visited');

        $('#slideShow').stop().animate({
            scrollLeft: Math.abs($('#slideWrap').offset().left) + $($anchor.attr('href')).offset().left + 100
        }, 1500);
        event.preventDefault();
    });
    //slide hover-effect        
    $('.nextPage').mouseover( function() {
        var $target = $(this).attr('href');
        $($target).css({
            opacity : '0.4',
            transition : 'opacity 1s ease-in-out'
        })
    }).mouseout( function() {
        var $target = $(this).attr('href');
        $($target).css(
            {
                opacity : '1',
                transition : 'opacity 1s ease-in-out'
            }
        );          
    });


    //This I need help with:
    $('#slideWrap').scroll(function(){
        var winScroll = $(window).scrollLeft();
        $('.slide').each(function(i) {
            if ($(this).position().left <= winScroll) {
                $('#crums li a').eq(i).addClass('visited');
            }
        });
    });    
});

Updated Fiddle

Upvotes: 0

Cobote
Cobote

Reputation: 395

Use #slideShow to get the current scroll position of element and for firing the scroll event.

I also added the removing of the class for the nav for when scrolling left.

$('#slideWrap').parent().scroll(function () {
    var winScroll = $(this).scrollLeft();
    $('.slide').each(function (i) {
        console.log($(this).position().left + " vs " + winScroll);
        if ($(this).position().left <= winScroll) {
            $('#crums li a').eq(i).addClass('visited');
        } else {
            $('#crums li a').eq(i).removeClass('visited');
        }
    });
});

JSFiddle Demo

Upvotes: 1

Related Questions