Skip to content

🎯 A plugin using localStorage to remember element scroll-position when closed the page.

License

Notifications You must be signed in to change notification settings

fengxianqi/remember-scroll

Repository files navigation

remember-scroll

NPM version npm download jsdelivr license npm bundle size Actions Status

English | 中文

A javascript plugin using localStorage to remember element scroll-position, which can auto scrolls to the last visit position when visiting the page again. Just 3kb gzipped.

文章介绍:

Demo

demo

Installation

npm i remember-scroll --save

CDN

<script src="https://cdn.jsdelivr.net/npm/remember-scroll@latest/dist/remember-scroll.min.js"></script>

You can get the latest version on jsdelivr.com.

Usage

Direct <script> Include

<html>
<head>
  <meta charset="utf-8">
  <title>remember-scroll examples</title>
</head>
<body>
  <script src="../dist/remember-scroll.js"></script>
  <script>
    new RememberScroll({
      pageKey: 'page1',
      maxLength: 5
    })
  </script>
</body>
</html>

ES6 module

import RememberScroll from 'remember-scroll'

new RememberScroll()

Use in Vue

<template>
  <div class="normal">
    <p v-for="item in 100" :key="item">{{ item }}</p>
  </div>
</template>

<script>
import RememberScroll from 'remember-scroll'

export default {
  name: 'normal',
  data () {
    return {
      rememberScroll: null
    }
  },
  mounted () {
    this.rememberScroll = new RememberScroll({
      pageKey: 'your_page_key'
    })
  },
  beforeDestroy () {
    // must remove EventListener
    this.rememberScroll.destory()
  }
}
</script>

If your page data is async, you can init RememberScroll in the async function, such as,

<template>
  <div class="home">
    <p v-for="item in ele" :key="item">{{ item }}</p>
  </div>
</template>

<script>
import RememberScroll from 'remember-scroll'
export default {
  name: 'home',
  data () {
    return {
      ele: [],
      rememberScroll: null
    }
  },
  mounted () {
    // async get data.
    setTimeout(() => {
      for (let i = 0; i < 50; i++) {
        this.ele.push(i)
      }
      // init
      this.rememberScroll = new RememberScroll({
        pageKey: 'home'
      })
    }, 2000)
  },
  beforeDestroy () {
    // must remove EventListener
    this.rememberScroll.destory()
  }
}
</script>

Options

Name Type Default Description
pageKey String '_page1' A unique identity of the page
maxLength Number 5 The max length of page count, prevent localStorage too big

Browser Support

This library relies on localStorage.

Chrome Edge Firefox IE Opera Safari
42+ ✔ 12+ ✔ 41+ ✔ 9+ ✔ 29+ ✔ 10+ ✔