2

Using JavaScript how can I scroll a HTML div if height of another DIV changes?

In the below code if mychat's height changes I need chat DIV's scroll bar should come down. My JavaScript is wrong can anybody correct it please.

My code is

<style type="text/css">
        #chat
        {
            height:250px;
            width:200px;
            overflow:auto;
            background-color:Aqua;
            padding:5px;
        }
    </style>
    <script type="text/javascript">
        function show() {
            var MyDiv = document.getElementById('mychat');
            var MyDiv2 = document.getElementById('chat');
            var sval;
            if(MyDiv.clientHeight != sval)
            {
              MyDiv2.scrollTop = MyDiv2.scrollHeight;
            }
            sval = MyDiv.clientHeight;
        }
    </script>
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
</asp:ScriptManager>
<div id="chat">
<asp:Timer ID="Timer1" runat="server" Interval="200" ontick="Timer1_Tick">
</asp:Timer>

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
    <div id="mychat" runat="server">

    </div>
</ContentTemplate>
<Triggers>
    <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
</div>

I am sorry I don't have enough knowledge in coding a JavaScript.

Mad coder.
  • 2,175
  • 8
  • 38
  • 53
  • what are you trying to accomplish? It might be that you don't even need javascript but could be fine using css… – maiwald Jan 27 '12 at 13:42
  • @mainwald - How can I achieve automatic scrolling of DIV layer `chat` whenever a new line is added to its innerlayer `mychat`? – Mad coder. Jan 27 '12 at 13:46

2 Answers2

1

This fiddle seems to be what you want - if not, it at least hopefully steers you in the right direction.

http://jsfiddle.net/7uvzd/7/

Adapted from code I've used from How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

Community
  • 1
  • 1
Mikeb
  • 6,271
  • 3
  • 27
  • 41
0

Using JavaScript, you're looking for the scrollTop property of your div.

a scrollTop of 0 means the scrollbar is at the top of the page.

Try: myDiv.scrollTop = myDiv.clientHeight or some similar metric.

Simon Sarris
  • 62,212
  • 13
  • 141
  • 171
  • Sorry, you are wrong! I need whenever DIV `mychat` height is changed then DIV `chat` has to scroll down. The code you gave is already in my question. I need how I detect height change in `mychat` DIV :) If height change is detected then only Scroll bar has to come down. – Mad coder. Jan 27 '12 at 14:06