jquery - Fixing this so it works if the element is not on the current page -
i found fix sticky header , works great, on of pages '.menu' class doesn't exist. i'm wondering how can adjust run if element on current page. when it's not there getting error message.
"uncaught typeerror: cannot read property 'top' of undefined" because .menu isn't there
// create clone of menu, right next original. $('.menu').addclass('original').clone().insertafter('.menu').addclass('cloned').css('position','fixed').css('top','0').css('margin-top','0').css('z-index','500').removeclass('original').hide(); scrollintervalid = setinterval(stickit, 10); function stickit() { var orgelementpos = $('.original').offset(); orgelementtop = orgelementpos.top; if ($(window).scrolltop() >= (orgelementtop)) { // scrolled past original position; show cloned, sticky element. // cloned element should have same left position , width original element. orgelement = $('.original'); coordsorgelement = orgelement.offset(); leftorgelement = coordsorgelement.left; widthorgelement = orgelement.css('width'); $('.cloned').css('left',leftorgelement+'px').css('top',0).css('width',widthorgelement).show(); $('.original').css('visibility','hidden'); } else { // not scrolled past menu; show original menu. $('.cloned').hide(); $('.original').css('visibility','visible'); } }
you check if .menu
exists before executing stickit()
.
like so:
if ($('.menu').length) { // create clone of menu, right next original. $('.menu').addclass('original').clone().insertafter('.menu').addclass('cloned').css('position','fixed').css('top','0').css('margin-top','0').css('z-index','500').removeclass('original').hide(); $(window).scroll(function(){ stickit(); }); }
you should replace setinterval
.scroll()
. it's not more elegant, might motivate optimize have.
here edited pen: codepen