How to capture position of a div so that on page reload i can have that position

Viewed 310

i wanted to capture the position of a scrolling capture area as shown in image below

enter image description here

so that on page reload any other scenario the state is preserved.

$(function(){

   setInterval(function(){
      window.location.reload();
   },90000);
  
});
.container{
  width:600px;
  height:300px;
 // background:red;
  overflow-y:auto;
  font-size:18px;
  line-height: 40px;
  padding-left: 14px;
  position: relative;
}

.center-band{
    position: fixed;
    z-index: 40;
    width: 100%;
    height: 70px;
    background: #0000003b;
    top: 50%;
    transform: translate(-50%, -50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  Lorem ipsum, dolor sit amet consectetur adipisicing elit. Adipisci sequi omnis officia, tempore nesciunt distinctio in inventore quia voluptate ducimus eius natus ex. Facilis excepturi distinctio sunt placeat deleniti error.
  
  Lorem ipsum dolor, sit amet consectetur adipisicing elit. Earum iste architecto dolores tempora officia vero, repellendus ab voluptas, eveniet dolore, cumque aliquam cum quas facilis aspernatur molestias perferendis eum nesciunt!
  
  
  
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Eligendi fugiat impedit quam, sit, sapiente, provident praesentium beatae non nostrum optio repellendus porro laboriosam quidem ipsa itaque? Voluptatem quam pariatur dolorem.
  
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Error, quisquam similique distinctio, perferendis accusantium quidem voluptatum architecto nulla ad adipisci provident possimus voluptatem ut animi aliquid quo hic ab. Assumenda?
  
  
  
  
  Lorem ipsum dolor sit amet consectetur, adipisicing elit. Fuga, sit corporis. Vitae facilis nesciunt alias consectetur rem, exercitationem, est possimus, beatae architecto suscipit expedita provident culpa. At eum sequi omnis
  
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Quas cum quaerat numquam ex vero, neque aliquid totam, explicabo error suscipit eius. Earum beatae voluptatum cupiditate iusto saepe quidem deserunt magnam?
  
  
  Lorem ipsum dolor, sit amet consectetur adipisicing elit. Commodi possimus excepturi dolores quasi, qui libero quia amet, ab facere quis nulla voluptatem, sunt necessitatibus! Animi voluptates quam minus odio excepturi!
  
  <div class="center-band"></div>
</div>

below is my codepen:

https://codepen.io/eabangalore/pen/jeKQwd/

Question: i'm trying to capture the position of band area, so that on page reload my text will be same

Please Help me, thanks in advance

5 Answers

Use:

Old Fascinated Way

As a document, is good to create a document structure of sections and titles. Every section may have an ID. So, you can use anchors to create URLS that points to specific page sections. You may create an internal navigation too using anchors. See more: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a

<a href="#my-section-1">My section 1</a>
<a href="#my-section-2">My section 2</a>
<section id="my-section-1">
  <h2>My section 1</h2>
  <p>Lorem ipsum ...<p>
</section>
<section id="my-section-2">
  <h2>My section 2</h2>
  <p>Lorem ipsum ...<p>
</section>

You are scrolling on the .container element, while the position of the div.center-band is fixed.

To store the information you can use localStorage, cookies, URL hashes or params; or even the history.

Local Storage

It will keep the information until you close the browser.

In this snippet: https://jsfiddle.net/gatsbimantico/1tzaq5g2/ I'm using local storage.

$(function() {
  var store = window.localStorage;
  var featureKey = 'container.scrollTop';

  function recoverScroll() {
    var scroll = store.getItem(featureKey);
    $('.container').scrollTop(parseInt(scroll, 10));
  }

  function saveScroll() {
    var scroll = $('.container').scrollTop();
    store.setItem(featureKey, scroll.toString());
  }

  if (!!store) {
    recoverScroll();
     $('.container').on('scroll', saveScroll);
   }  

});

You can do this by using two things localStorage and jquery scroll functions as follows:

$(function(){
    let heightOffset =localStorage.getItem("heightOffset");
    $('.container').scrollTop(heightOffset);

    setInterval(function(){
        heightOffset = $('.container').scrollTop();
        localStorage.setItem("heightOffset", heightOffset);

        window.location.reload();
    },90000);
});

here before loading localStorage.setItem("heightOffset", heightOffset) sets the previous scroll offset position, further on reload you can get the initial offset position from localStorage.getItem("heightOffset"), and keep the scroll exactly at that position.

Here you can view the working example.

I suspect you want to return the scroll position back to what the User left on. This will not use the fixed position, but capture the current scroll position.

Consider the following example: https://jsfiddle.net/Twisty/0u9rdym7/14/

JavaScript

$(function() {
  function recordScroll(val) {
    var pos = 0;
    if (typeof val !== undefined) {
      pos = val;
    }
    console.log("Save", pos);
    localStorage.setItem('scrollVal', val);
  }

  function getScroll() {
    var pos = localStorage.getItem('scrollVal') || 0;
    pos = parseInt(pos);
    console.log("Get", pos);
    return pos;
  }

  function returnToPos($t, val) {
    var pos = 0;
    if (typeof val === 'undefined') {
      pos = getScroll();
    } else {
      pos = val;
    }
    pos = parseInt(pos);
    console.log("Return", pos);
    $t.scrollTop(pos);
  }

  $(".container").scroll(function(e) {
    var pos = $(this).scrollTop();
    clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function() {
      recordScroll(pos);
      console.log("Haven't scrolled in 250ms!");
    }, 250));
  });
  returnToPos($(".container"));
  recordScroll($(".container").scrollTop());
});

You will want to record the current position, get the position, and return the container to that position. As suggested, since the page will be reloading, localStorage or cookies is a good way to do this. During Scroll actions, we need to know when scrolling stops and we also want to know the scrollTop value.

When scrolling stops, we can save the value to localStorage. When reload happens, the page will collect the stored value and return the scroll to that position.

Hope that helps.

A simple solution

Attach onscroll event to your div.

function setScroll(){
    document.getElementById("myDiv").scrollTop = localStorage.getItem('scrollTO')||0;
}
<body onload="setScroll()">

<div id="myDiv"  onscroll="localStorage.setItem('scrollTO',this.scrollTop)">

<!-- your text goes here-->

</div>
</body>

When you scroll, the scrollTop is saved to localStorage and when you reload the page, you can read that from localStorage and scroll your page to the position from where the user left.

Related