Maverickk
Maverickk

Reputation: 33

change css display when user scrolls down. Without jQuery

Actually i want to create a "Scroll to the top" button without jQuery.
The go to the top function is already working.
Now I need to automate the display: none to display: block when the user scrolls down the page. And the other way when it gets back to the top.

<a href="#ancor-top" id="GoTop">Top</a>

#GoTop {
    display: none;
    position: fixed; 
    bottom: 20px; 
    right: 30px; 
    z-index: 99;
    border: none; 
    outline: none;
    background-color: red; 
    color: white; 
    cursor: pointer; 
    padding: 15px; 
    border-radius: 10px; 
}

Upvotes: 2

Views: 671

Answers (1)

Shadow Fiend
Shadow Fiend

Reputation: 1829

Try this

var goTop = document.getElementById('GoTop');
window.onscroll = function(ev) {
  if (this.pageYOffset > 100) {
    goTop.style.display = 'block';
  } else {
    goTop.style.display = 'none';
  }
};
div {
  height: 200vh;
  width: 100%;
}

#GoTop {
  display: none;
  position: fixed;
  bottom: 20px;
  right: 30px;
  z-index: 99;
  border: none;
  outline: none;
  background-color: red;
  color: white;
  cursor: pointer;
  padding: 15px;
  border-radius: 10px;
}
<a href="#ancor-top" id="GoTop">Top</a>
<div>
</div>

Upvotes: 2

Related Questions