Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if element is either above or below fold of page

I have some pages that have multiple input boxes that users can enter text into. Some of these are required to fill in before they click the 'next' button. I have validation errors popping up for the user to see however if the question if off the page I would like the page to scroll to it instead of them having to search for the missing/wrong field.

I have a scroll to in place, but I am having trouble ascertaining what element what element to scroll to. For example if the input in above the fold of the page I would like to scroll to the label so they can see the error and the input. But if it is below the fold I would then like to select the input so that will show above the fold. Does that make any sense?

I guess what I'm really asking is, is there a way to determine where the element is on the page. And if it is above the fold scroll to the label, but if it is below the fold then scroll to the input?

Right now I am just scrolling to error's input field.

$(".container-content").mCustomScrollbar("scrollTo",$('.container-content').find('input.error:first')); //Yes I am using a plugin for the scroll

if I just scroll to the label then it looks like this. enter image description here

like image 213
zazvorniki Avatar asked Nov 20 '25 13:11

zazvorniki


1 Answers

You can use this function: Jsfiddle

function isElementInViewport (el) {
    var rect = el[0].getBoundingClientRect();
    return (rect.top>-1 && rect.bottom <= $(window).height());
}

originally posted Here

New api which you can use in just 11 extra steps lol https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#Browser_compatibility

like image 104
Muhammad Umer Avatar answered Nov 22 '25 04:11

Muhammad Umer