Custom scrollspy jquery only works when handcoded -
i've been stuck while now. i'm trying make own scrollspy. thing works when handcoded, , if try through variables keeps giving me
$(document).ready(function() { setinterval(check, 100); }); function isscrolledintoview() { var docviewtop = $(window).scrolltop(); var docviewbottom = docviewtop + $(window).height(); var year = $('.year').eq(2).attr("class"); var test = year.split(' '); test = test[1]; var elemtop = $(".item."+test).offset().top; var elembottom = elemtop + $(".item."+test).height(); return ((elembottom <= docviewbottom) && (elemtop >= docviewtop)); } var check = function(){ var itemslength = $('.year').length; (var = itemslength-1; >= 0; i--) { var year = $('.year').eq(i).attr("class"); var yearsplitted = year.split(' '); if(isscrolledintoview()) { $(".year.2016").addclass("item-active"); } else { $(".year.2016").removeclass("item-active"); } } };
you can see @ first function
var elemtop = $(".item."+test).offset().top;
if try through variables, doesn't work.
edit: used wrong loop.
in javascript, variable declarations hoisted, not initializations. consequently, when call "setinterval" in document.ready function, "check" function variable undefined.
if want use variable "check" function, try moving set interval call end of script so:
function isscrolledintoview() { var docviewtop = $(window).scrolltop(); var docviewbottom = docviewtop + $(window).height(); var year = $('.year').eq(2).attr("class"); var test = year.split(' '); test = test[1]; var elemtop = $(".item."+test).offset().top; var elembottom = elemtop + $(".item."+test).height(); return ((elembottom <= docviewbottom) && (elemtop >= docviewtop)); } var check = function(){ var itemslength = $('.year').length; (var = itemslength-1; >= 0; i--) { var year = $('.year').eq(i).attr("class"); var yearsplitted = year.split(' '); if(isscrolledintoview()) { $(".year.2016").addclass("item-active"); } else { $(".year.2016").removeclass("item-active"); } } }; $(document).ready(function() { setinterval(check, 100); });
this should script firing, suspect you'll need bit more work have scroll spy extension functional.
Comments
Post a Comment