tags:

views:

64

answers:

3

I am using javascript to change the display of a div tag with an onclick event. The div is at the bottom of the page, when and/or if needed the user can open the div. How can I get the page to scroll down when this div is changed to display:block?

FYI: I have tried

var objDiv = document.getElementById("the_div_id");
objDiv.scrollTop = objDiv.scrollHeight;

The page just won't scroll down. Any ideas?

A: 

Something like this would work

Add an anchor by the div

<a href="#div" id="showDivTrigger">
<a name="div"></a>
<div style="display:none;">
contents
</div>
<script>
var element = document.getElementById('#div');
element.style.display = '';
</script>
Sherdog
This did work for the first instance. After the first call to the div, it didn't work again. I used:
MP123
location.href=location.href + '#tt' then at the bottom of the page <a name="tt"></a>
MP123
+3  A: 
var objDiv = document.getElementById("the_div_id");
objDiv.scrollIntoView();
mplungjan
This one is the answer. Works totally perfect.
MP123
Great - so please click the green tick mark next to my answer. Or are you not yet allowed to for SO?
mplungjan
Well here is another question; where can I find the simple quick instructions for using this website? I have no idea how to use this site, I'm just winging it. LOL!
MP123
Haha. I know how you feel. It can be very opaque. For example you are not allowed to ask how this site works here. You need to go to META.stackoverflow.com http://meta.stackoverflow.com/questions/5234/how-does-accepting-an-answer-work ;)))
mplungjan
A: 

scrollTop only makes sense on elements which themselves have a scrollbar (or do not, but can be scrolled). From the MSDN documentation: This property is always 0 for objects that do not have scroll bars. For these objects, setting the property has no effect.

You chould set body.scrollTop instead (or use window.scrollTo which has the same effect), for which you need the absolute position of the element in the page, which you can get by walking up the element's offsetParent chain and summing up offsetTop distances. You are probably better off using a framework, e.g. jQuery's offset method, than doing this manually. (Of course, if you only need to jump to the element and not visually scroll, then mplungjan's solution is the simplest.)

Tgr