How to change the properties of a sticky up arrow button based on its position?

I have a sticky up arrow image for my webpage as follows:


<a href = "#navbar-scroll"><img src = "images/sticky-btn-light.png" id = "myBtn" alt = "sticky-up-button"></a>

And CSS:

#myBtn {
    visibility: hidden;
    position: fixed;
    bottom: 50px; 
    right: 30px; 
    z-index: 99; 
    cursor: pointer;
    padding: 15px; 
    border-radius: 10px;
    width: 5%;
    opacity: 0.5 ;

The button disappears when the user scrolls down and appears when the user scrolls up based on this JS code.

window.onscroll = function(e) {
    console.log(this.oldScroll > this.scrollY);
    if((this.scrollY == 0) || (this.oldScroll < this.scrollY)  ){
        document.getElementById('myBtn').style.visibility = 'hidden';
    else if(this.oldScroll > this.scrollY){
        document.getElementById('myBtn').style.visibility = 'visible';
    this.oldScroll = this.scrollY;

Now, I want to change the color of the button based on its changing position on the screen. As I scroll the page, the sticky button will be in different sections as below.Web page layout1 If the sticky button is in Section A, it should be red. And if it is in Section B, it should be blue. Web page layout2

For this, I need the id of the section in which the sticky button is overlapping at any given moment. Is there any way to get that information through JavaScript?

Read more here:

Content Attribution

This content was originally published by Aayush Lamichhane at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: