最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to capture position of a div so that on page reload i can have that position - Stack Overflow

programmeradmin1浏览0评论

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

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=".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>

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

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./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

Share Improve this question edited Feb 2, 2023 at 8:05 Mayank Kumar Chaudhari 18.8k13 gold badges67 silver badges155 bronze badges asked Oct 21, 2018 at 4:32 EaBengaluruEaBengaluru 812 gold badges30 silver badges72 bronze badges 10
  • If/When you reload a page any changes or stored within javascript will be lost and execute with no memory of anything before the reload/refresh. You can use cookie/localstorage to save data that you can later access if the client hasn't disables them. – NewToJS Commented Oct 21, 2018 at 4:37
  • @NewToJS, i want to store it into localStorage so that page reload does not affect – EaBengaluru Commented Oct 21, 2018 at 4:38
  • But you haven't shown any attempt to use localStorage in the source code provided. Stackoverflow isn't a free programming service so please include your attempt(s) so a detailed answer can be given to why your attempt didn't work. – NewToJS Commented Oct 21, 2018 at 4:39
  • @NewToJS, i'm very new programmer, still learning don't know much, that is why i haven't shown any attempt – EaBengaluru Commented Oct 21, 2018 at 4:41
  • Then I can only remend you do some research and at least attempt to achieve your goal rather than expecting others to code it for you. You will benefit more from the research and own attempts. – NewToJS Commented Oct 21, 2018 at 4:42
 |  Show 5 more ments

5 Answers 5

Reset to default 5

Use:

  • https://developer.mozilla/en-US/docs/Web/API/Window/pageYOffset to obtain the position.

  • https://developer.mozilla/it/docs/Web/API/Window/localStorage to save and retrive the position

  • https://developer.mozilla/en-US/docs/Web/API/Window/scrollTo to scroll

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/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/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/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.

发布评论

评论列表(0)

  1. 暂无评论