javascript - Responsive scrolltop -


im using following code detect when object should become 'sticky' , stay fixed in content.

var $window = $(window),     $stickyel = $('#single-post-details'),     eltop = $stickyel.offset().top;  $window.scroll(function() {     $stickyel.toggleclass('sticky', $window.scrolltop() + 52 > eltop); }); 

however make responsive. means somehow needs detect height of banner above first doesn't trigger @ wrong point.. here fiddle example.

the problem on resize, top position of sticky element change. solve that, should not check height of image, recalculate top position.

the use of .resize event usefull here. on callback, update global variable :

var $window = $(window),     $stickyel = $('#single-post-details'),     eltop = $stickyel.offset().top;  $window.on({     resize : function(){         eltop = $stickyel.offset().top;         $window.trigger('scroll');     },     scroll : function() {         $stickyel.toggleclass('sticky', $window.scrolltop() + 20 > eltop);     } }); 

note: trigger('scroll') important prevent sticky element go on image while expanding window.

fiddle


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -