how to determine, using jquery, if the element is visible on the current page view. I'd like to add a comment functionality, which works like in facebook, where you only scroll to element if it's not currently visible. By visible, I mean that it is not in the current page view, but you can scroll to the element.
Summary. Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport. Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.
$(selector).scrollTop(position) Parameter. Description. position. Specifies the vertical scrollbar position in pixels.
Use the href Property to Scroll to an Element in JavaScript href = "#"; location. href = "#myDiv"; Here #myDiv is the ID of the required <div> tag.
Live Demo
Basically you just check the position of the element to see if its within the windows viewport.
function checkIfInView(element){ var offset = element.offset().top - $(window).scrollTop(); if(offset > window.innerHeight){ // Not in view so scroll to it $('html,body').animate({scrollTop: offset}, 1000); return false; } return true; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With