Adi
Adi

Reputation: 35

How to scroll to an ID inside a div?

The code contains a div which should scroll to a special id inside that. I have tried this code, but it does not scroll at all and there is no error being thrown as well.

var divToHighlight = document.getElementById(mID);
divToHighlight.style.backgroundColor ="#F5F0C9";
var topPos = divToHighlight.offsetTop;	
document.getElementById("My-Div").scrollTop = topPos;

I have also checked this post but I can't figure out why my code does not work.

Upvotes: 1

Views: 223

Answers (1)

ak_
ak_

Reputation: 2815

You probably want to scroll the parent element, not your div. Something like this would work.

var divToHighlight = document.getElementById(mID);
divToHighlight.style.backgroundColor ="#F5F0C9";
var topPos = divToHighlight.offsetTop;  
divToHighlight.parentElement.scrollTop = topPos;

See it working here: https://jsfiddle.net/igor_9000/L6bvwg20/1/

Hope that helps!

Upvotes: 1

Related Questions