Awsme Sandy
Awsme Sandy

Reputation: 1408

How to detect if the scroll value is more then the windows height?

In my case the header become fixed on scroll, but only visible when when we scroll up a little bit, and when we scroll down it hides, thats all working fine.

Requirement: The header should only visible if i scroll up and the scroll should be at least of the windows height. For example if my windows height is 700 px, then the header should only visible once i scroll the page 700px up, and hides instantly when i scroll it down.

Thanks in advance.

Upvotes: 1

Views: 1123

Answers (3)

Jimmy
Jimmy

Reputation: 73

1.get position relative to body get offset position relative to parent element, if parent node is not body, continue.

2.get scroll position it depends on how to scroll. if native scroll, get scroll value by element.scroll is ok. if use transform, have to get transform x or y value

3.body position - scroll position

example:

export const getBodyLeft = (e:HtmlElement) => {
let offsetLeft = el.offsetLeft;
const offsetParent = el.offsetParent;
if (el.offsetParent && el.offsetParent.nodeName.toUpperCase() !== 'BODY'){
    offsetLeft += getBodyLeft(<HTMLElement>el.offsetParent);
}
return offsetLeft

}

export const getViewTop = (el: HTMLElement, view: HTMLElement) => {
const bodyTop = getBodyTop(el);
const scrollView = view || document.body;
let scrollTop = scrollView.scrollTop;
let transformTop = 0;
const transform = getComputedStyle(<Element>view).transform;
if (transform) {
    const matrix = transform.match(/((-|\d|\.)+)/g) || [];
    const len = matrix.length;
    if (matrix && len > 0) {
        transformTop = Math.abs(Number(matrix[matrix.length - 1]));
    }
}
scrollTop += transformTop;
return bodyTop - scrollTop;

}

Upvotes: 0

Chandra Kumar
Chandra Kumar

Reputation: 4205

Use this code:

Demo: http://output.jsbin.com/ricohevexu

<script>
$(window).scroll(function (e) {
  var height = $(window).scrollTop();
  var winheight = $(window).height();
  if(height  > winheight) {
    // Do something
    console.log("Scroll height is more that window height!");
  }
});
</script>

Upvotes: 0

Paweł Kwiatkowski
Paweł Kwiatkowski

Reputation: 79

Try this:

 $(window).scroll(function(){
  var containerHeight = $('.section-1').height();
  var windowHeight = ( $(window).scrollTop() );
  if( windowHeight > containerHeight ){
   $(".header").removeClass('header-solid');
  } else {
   $('.header').addClass('header-solid');
  }
 });

Upvotes: 1

Related Questions