Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll if element is not visible

Tags:

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.

like image 987
macpak Avatar asked Jun 02 '11 14:06

macpak


People also ask

How do you know if an element is visible in scroll?

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.

What is $( window scrollTop ()?

$(selector).scrollTop(position) Parameter. Description. position. Specifies the vertical scrollbar position in pixels.

How do I scroll to a specific element?

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.


1 Answers

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; } 
like image 181
Loktar Avatar answered Oct 20 '22 00:10

Loktar