1

How to properly detect when a static element overlaps a fixed element y position on event scroll ?

I'm sure I've done this before, but at the moment I missing something (example here http://jsbin.com/hetovoduwi/edit?css,js,console,output).

js:

window.addEventListener('scroll', function () {
  console.log('win y:' + window.scrollY);

var b = document.querySelector('.b').getBoundingClientRect();

console.log(b);

/*
console.log('(b.top+b.height)', (b.top+b.height));

  console.log('window.scrollY - 50', window.scrollY - 50)
*/
});

html:

  <div class="a"></div>

  <div class="b"></div>

css:

.a {
  position: fixed;
  width: 50px;
  height: 50px;
  background: red;
  top: 50px;
}
.b {
  margin-top: 30vh;
  width: 50px;
  height: 50px;
  background: blue;
}

body {
  height: 100vh;
}

1 Answer 1

5

b will overlap a when its top position will be less then a.top + a.height and then a.top is bigger then b.top + b.height - http://jsbin.com/peqiximugo/1/edit?css,js,console,output

var log = document.querySelector('.log');

window.addEventListener('scroll', function () {

var b = document.querySelector('.b').getBoundingClientRect(),
    a = document.querySelector('.a').getBoundingClientRect();
  
  
  if (b.top <= a.top + a.height && b.top + b.height > a.top) {
    log.innerHTML = 'overlaps'
  } else {
    log.innerHTML = 'doesn\'t overlaps'
  }

});
.a {
  position: fixed;
  width: 50px;
  height: 50px;
  background: red;
  top: 50px;
}
.b {
  margin-top: 30vh;
  width: 50px;
  height: 50px;
  background: blue;
}

body {
  height: 100vh;
}

.log {
  position: fixed;
  top: 50px;
  left: 80px;
}
<div class="a"></div>
<div class="b"></div>


<div class='log'></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @t1m0n that makes sense! I was using the scrollY for some reason :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.