How to get item position using jquery

I am trying to change the absolute position of the sidebar to fixed. The idea is that the sidebar will be absolute until it touches the footer, and then it will be fixed. So the code below works fine on my large monitor, but on my small monitor the sidebar is fixed before it gets into the footer, and I assume that on the large monitor the sidebar will work in the footer, and the code below will not start.

$(document).scroll(function() { if ($(this).scrollTop() < 5953) { $('.hanger').addClass(' hanger sidebar'); $('.xoxo').removeClass('xoxo2 ') $('.xoxo').css("position", "fixed"); } }) 

So, is there a way to get the number 5953 dynamically? I tried: var value = $('#footer').scrollTop() and var value = $('#footer').offset().top , and then pass the value variable instead of a fixed number

Here is the daemon http://aurelslab.co.uk/ - if your monitor is larger or smaller than mine, you will see that the sidebar is not working as it should

thanks

+4
source share
2 answers

Is this what you are looking for?

 var value = $(window).height() + $(window).scrollTop(); var elementTop = $('#pagefooter').offset().top; if( value >= elementTop ) { $('.hanger').removeClass('sidebar'); $('.xoxo').addClass('xoxo xoxo2') $('.xoxo').css("position","absolute"); } else if( value < elementTop ) { $('.hanger').addClass(' hanger sidebar'); $('.xoxo').removeClass('xoxo2 ') $('.xoxo').css("position","fixed"); } 

I tested it locally and seemed to work regardless of the size of your window. It basically adds the size of the window to scrolltop to see if the footer has moved to the viewport yet.

2 notes

When scrolling on a mobile device (for example, with iOS), the scroll event is triggered when all pulses end. Thus, you will not see the smooth movement that you see on the desktop.

And the identifier of your footer is not footer , but pagefooter . :)

+2
source

To access the footer element, you can use the element identifier or element.

Example:

  • To access the footer element: $('footer')
  • To access the footer: $('#pagefooter')

Just do this to find the current position of the footer.

 var currentPosition = $('footer').position().top - $(window).height(); 

I explained to you LIVE DEMO .

0
source

All Articles