1

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.

Community
  • 1
  • 1
Adi
  • 35
  • 11

1 Answers1

1

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!

Adam Konieska
  • 2,805
  • 3
  • 14
  • 27
  • I want to scroll inside the div. the mID is an element inside the Div which should come to the top of the Div. Actually I have no problem when my data was inside the body, but I had to put it inside a scrolling Div. But this one does not work now. – Adi Mar 04 '16 at 19:25
  • @adonis I updated the answer to scroll the parent div, instead of the body. – Adam Konieska Mar 04 '16 at 19:30
  • 1
    Thanx Adam. your code helped me pretty much. the problem was that my Div had a heigth of 500. I had to reduce it from topPos to stay at correct position. Now its working :) – Adi Mar 04 '16 at 20:16