Reputation: 467
Here is my setup: http://jsfiddle.net/REGUs/
As you can see by clicking on the menu on the left, the page scrolls to the relevant information and the menu item changes its appearance to a white background etc.
I would like the page to check where abouts it is and then update the css on the list respectively so that if the page is looking at the second heading the menu changes the second headings css to the style it would be had they clicked it. I know this is quite wordy and probably doesn't make much sense and im sorry.
Here is how i thought it would work:
I don't know how many headings are on each page (i do in theory but there are a lot of pages and i would rather have something dynamic). So i would use $("h2").length
to check the amount of headers. Then perhaps have a loop to get the distances of each of these (stored in an array?), then every time window scrolls, it starts loading or changes size, a function will capture where the screen is and then updates the css. If this is how you would solve it could you help me put it together, if there is another better way (probably is as i don't really use javascript) can you please let me know.
thanks, Chris
Upvotes: 2
Views: 144
Reputation: 1195
In case you dont want everything from bootstrap here is what you need to do
http://jsfiddle.net/6t83p/1/ some time spent on it but its always fun :)
$('.selectedNav').css( 'background-color', 'white');
$('.selectedNav').css( 'border-right', 'none');
$('.servicesNavItem').click(function () {
$(this).parent().css( 'background-color', 'white');
$(this).parent().css( 'border-right', 'none');
$('.selectedNav').css( 'background-color', '#eeeeee');
$('.selectedNav').css( 'border-right', '1px solid #c7c7c7');
$('.selectedNav').toggleClass("selectedNav");
$(this).parent().toggleClass("selectedNav");
});
var y = $('.servicesLeft').offset().top - 50;
$(window).scroll( function() {
if ($(window).scrollTop() > y)
$('.servicesLeft').addClass('floating');
else
$('.servicesLeft').removeClass('floating');
});
$('#sideNav li a').click(function(){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
/***** ADDED THE FOLLOWING CODE ******/
// get positions of all linked href
var x = {};
$('#sideNav a').each(function(){
var href = $(this).attr('href').replace('#','');
x[href] = $('#'+href).offset().top;
});
$(document).on('scroll', function(){
var current_top = window.pageYOffset;
console.log(current_top);
var active = '';
var min_value = 9999999;
$.each(x, function(index, value) {
// some big value
if(value >= current_top && value < min_value)
{
console.log(min_value);
min_value = value;
active = index;
}
});
$('#sideNav li').removeAttr('style');
$('#sideNav a[href="#'+active+'"]').parent('li').css({'background-color': 'white', 'border-right-style': 'none'});
});
Upvotes: 2
Reputation: 6002
i guess this post will would help you
jQuery to change content in div based on scroll position
Happy coding :)
Upvotes: 1