2

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; 
}

1 Answer 1

2

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>

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

5 Comments

Without using jquery you can acheive this by using Bootstrap section and Scrollspy.
@KarenBezas did you put the code in a separate file? if so check the path. If its the same path did you put it at the top of the page? then wrap the javascript with the window.onload function or just simply put the code before the end of body tag..
It was in the beginning of the body tag. I've moved it to the before the end of the body tag, and now it worked ;) thanks!
@KarenBezas I'm glad I was able to help :)
pageYOffset is deprecated

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.