Search code examples
javascriptjqueryheighttogglesticky-windows

I need help figuring out how to toggle an element once vertical height of window is scrolled


I'm trying to toggle a div from relative to fixed when I scroll down 200px using javascript. When I reach 200px from the top of the window, my div should toggle to fixed. And when I'm above that 200px from the top it should go back to relative. Does anyone have an idea on how to do this?


Solution

  • Something like:

    $(window).on('scroll', function() {
        $("#myDivID").css({
           position: $(this).scrollTop()<200?'relative':'fixed',
           top: $(this).scrollTop()<200?'200px':'0px'
        });
    });
    

    You'll probably also have to reset the top position of the element.