user3550879 user3550879 - 7 months ago 15
Javascript Question

changing div css at a specific page location

I have the following code which puts a button fixed to the top of the page which overlays the content/images as the page scrolls.

HTML

<div id="btn">button</div>

... images ...

... content ...


css

#btn {
position: fixed;
z-index: 999;
color: #fff;
top: 0; right: 0;
}


I want to put an 'anchor' or something when the button reaches that point the #btn css changes to color: #000;

so essentially

<div id="btn">button</div>

... images ...

anchor changing the css

... content ...


EDIT: the amount of content and images is not controlled by me so I don't know the distance from the top or bottom

Answer

I think i have a javascript based solution for you. I hope this will help

https://jsfiddle.net/n9ssbL8h/1/

window.onscroll=function(){
	if(document.getElementById('btn').getBoundingClientRect().top>= document.getElementById('header').getBoundingClientRect().top){
  document.getElementById('btn').style.color = '#fff';
  }else{
  document.getElementById('btn').style.color = '#000';
  }
}
#btn { 
  position: fixed;
  z-index: 999;
  top: 0; right: 0;
}
#header{
  margin-top: 100px;
  height: 400px;
  background-color: red;
}
#content{
  height: 400px;
  background-color: green;
}
<div id="body">
<a id="btn">Button </a>
<div id="header">
Header
</div>
<div id="content">
Content
</div>
<div id="images">

</div>
</div>