Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Coordinates of an element on page scroll

I am having this problem where i have a set of 6 UL's having a common class x.Each of them consist of a specific section of the page.Now i have 6 menus that are related to each of the section.What i have to do is highlight the menu when its related section is in users view. For this i thought that may be jQuery position(); or offset(); could have helped but they give the top and left of the element.I also tried using jQuery viewport plugin but apparently view port is big it can show more than one UL at a time hence i cant apply element specific logic here.I am not familliar to this but does anything changes of an element on scrolling?If yes then how to access it?

Please share your views.

Regards Himanshu Sharma.

like image 368
techie_28 Avatar asked Mar 23 '12 04:03

techie_28


1 Answers

Is very easy to do it using jQuery and a dummy fixed HTML block that helps you find the current position of the viewport.

$(window).on("scroll load",function(){  
    var once = true;
    $(".title").each(function(ele, index){
        if($(this).offset().top > $("#viewport_helper").offset().top && once){              
            var index = $(this).index(".title");
            $(".current").removeClass('current')        
            $("#menu li").eq(index).addClass('current')
            once = false;
        }
    });     
})

Check out a working example: http://jsfiddle.net/6c8Az/1/


You could also do something similar with the jQuery plugin, together with the :first selector:

$(window).on("scroll load",function(){  
    $(".title:in-viewport:first").each(function(){
        var index = $(this).index(".title");
        $(".current").removeClass('current')        
        $("#menu li").eq(index).addClass('current')
    }); 
})
like image 175
Ivan Castellanos Avatar answered Oct 14 '22 14:10

Ivan Castellanos