Neia
Neia

Reputation: 69

How to move to the top of the element?

I know that .scrollTo(0,0) works for the window and returns you to the top of the page. But my goal is to return to the top of the certain element on the page. How can I do that?

function returnToTopElement(clickingObjId, element){
	let clickOn = document.getElementById(clickingObjId);
	let topElement = document.getElementById(element);
	clickOn.addEventListener('click', function(){
		topElement.scrollTo(0,0);
	});
};

returnToTopElement("top-button", "elem-b");
    .menu{
	  position: fixed;
	  background-color: red;
	  width: 100%;
	  height: 30px;
	  top: 0;
    }
    .elem-a{
      height: 200px;
      width: 200px;
      background-color: #f6f6f6;
      color: black;
    }
    .elem-b{
      height: 300px;
      width: 200px;
      background-color: #263B42;
      color: white;
    }
    .top-button{
      margin-top: 200px;
      cursor: pointer;
    }
    .top-button:hover{
      background-color: #b2b2b2;
    }
    <div class="menu"> Menu </div>
    <div>  
      <div class="elem-a"> a </div>
      <div class="elem-b" id="elem-b"> 

      b

      <p class="top-button" id="top-button"> Return to the top </p>
      </div>
    </div>

Upvotes: 2

Views: 105

Answers (1)

Hurried-Helpful
Hurried-Helpful

Reputation: 2010

HTMLElement.offsetTop is the distance between this element's top border to its offsetParent's top border, not to the top of the document. It's also oddly complicated to calculate the relative distance between two elements. In your case, you can calculate it using the following:

topElement.getBoundingClientRect().top - document.documentElement.getBoundingClientRect().top

But this doesn't account for the top margin if there's any. So you might have to go further IF you want to include the top margin like this.

topElement.getBoundingClientRect().top 
- topElement.getComputedStyle().getPropertyValue('margin-top')
- document.documentElement.getBoundingClientRect().top

You might be wondering if there's a less cumbersome way, but really, this is what you have to do in most cases.

Upvotes: 1

Related Questions