Skip to content
Advertisement

Stop Div scrolling to the top at Page Refresh using Jquery

I have two pages with the same css class and the same id, but since they are on different pages, the id is the separator.

Page 1) Got a Div being refreshed every 5 seconds. The div has scrolling set to scroll so that user can scroll, but when the refresh happens the div scrolling goes back to the top. Any ideas/written script on how I can keep the scroll position after the div is refreshed?

Page 2) This is similar to page 1, other from, When users come to this page the first time, I want the scroll position to be at the bottom, then when the refresh happens, I want to keep the scroll position of the div wherever I have scrolled to after its refreshed

Bottom Line: I’m relatively new to Front-End design, so Please, your contribution should be something I would understand easily or close to easy This is my css

 .msg_container_base{
      background: #fff;
      margin: 0;
      padding: 0 10px 10px;
      max-height:400px;
      overflow-x:hidden;
      overflow-y:auto;
    }

    .msg_container_base::-webkit-scrollbar-track
    {
        -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
        background-color: #fff;
    }

    .msg_container_base::-webkit-scrollbar
    {
        width: 12px;
        background-color: #fff;
    }

    .msg_container_base::-webkit-scrollbar-thumb
    {
        -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
        background-color: #fff;
    }

This is my java script for loading and refreshing

 <script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$("#grid").load('mai/ #grid');
}, 20000); // refresh every 10000 milliseconds

</script> 
        <div id="grid">

        @RenderPage("~/mai.cshtml") 
      </div>

Advertisement

Answer

See this Fiddle : http://jsfiddle.net/tu6fj8jq/7/

Using element.scrollTop you can store the scroll position in the div before you refresh it

This outputs the scroll position in another element when div is scrolled :

$("div").on("scroll", function()
{
    $("span").html($("div")[0].scrollTop);
});

For the second part, you can scroll the div to the bottom at page load like this :

$(function()
{
  $("#bottom")[0].scrollTop = $("#bottom")[0].scrollHeight - $("#bottom").height();
});
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement