Home > front end >  HTML javascript saved viewing position after re-loading html
HTML javascript saved viewing position after re-loading html

Time:10-13

I have this code where I can save the position of my html file like a bookmark and the box jumps to the position of the last save. Both work well.

When I re-open the document again it goes to the position as planned, but the box is not there anymore. (the box jumps back to the start)

How can I keep the box at the saved point after re-loading the html?

Here is my JSFiddle

Thank you very much in advance!

HTML:

<div class="box"></div>

CSS:

#takeMeToSave {
  background-color: lightblue;
  position: fixed;
  top: 0;
  cursor:pointer;
  border-radius:4px;
  padding:3px;
}

#box {
  position: absolute;
  background-color: black;
  opacity: 0.5;
  height: 2.5em;
  width: 100%;
  left: 0;
  top: 0px;
  transition: 0.3s top;
  pointer-events:none;
}

JS:

  var test = "test";
  try {
      localStorage.setItem(test, test);
      localStorage.removeItem(test);
      return true;
  } catch(e) {
      return false;
  }
}

function getTotalHeight() {
  return document.body.clientHeight;
}

function getSavedPercent() {
  var percent = storageSupported ? loadFromStorage() : loadFromCookie();
  return (percent == null || percent == "") ? 0 : percent;
}


/******* Save *******/

function saveInStorage() {
  localStorage.setItem("scrollPercent", (document.documentElement.scrollTop / getTotalHeight()));
  
}

function saveCookie() {
  var expDate = new Date();
  expDate.setDate(expDate.getDate()   7); // start over if it's been more than ___ days
  document.cookie = "scrollPercent="   (document.documentElement.scrollTop / getTotalHeight())
                "; "   expDate;         
}


/******* Load *******/

function loadFromStorage() {
  return localStorage.getItem("scrollPercent");
}

function loadFromCookie() {
  return document.cookie.replace(/(?:(?:^|.*;\s*)scrollPercent\s*\=\s*([^;]*).*$)|^.*$/, "$1");
}



/******* Handler *******/

var saveButton = document.getElementById("saveButton");
var saved = document.getElementById("saved");
var takeMeToSave = document.getElementById("takeMeToSave");
var cordinateCont = "";
var cordinateBtn = ""
var boxMove = document.getElementById("box");


takeMeToSave.style.display = "none"
saveButton.onclick = function(e) {
  storageSupported ? saveInStorage() : saveCookie();
  saved.style.visibility = "visible";
  setTimeout(function() {
    saved.style.visibility = "hidden";
  }, 1500);
  cordinateCont = e.pageY; //where is the click according to content including scroll content 
  cordinateBtn = e.clientY; //cordinateBtn is where it is clicked inside btn
  takeMeToSave.style.display = "block";
  boxMove.style.top = cordinateCont  60 - cordinateBtn   'px';
};

takeMeToSave.onclick = function() {
  storageSupported ? saveInStorage() : saveCookie();
  window.scrollTo({
    top: cordinateCont   60 - cordinateBtn,
    left: 0,
    behavior: 'smooth'
  });
  //1 is borderWidth of btn and 50, cordinateBtn, 1 is subtracted from position to remove wherever it is clicked on btn and only change with respect to top of window screen of content
};



/******* Logic *******/

var storageSupported = checkStorageSupport(),
  percent = getSavedPercent();

if (percent > 0) {
  if (confirm("Would you like to continue reading where you left off?")) {
      document.documentElement.scrollTop = percent * getTotalHeight();
  };
}

CodePudding user response:

I see you have already used LocalStorage very well.

You could save the button position as you've done with the scroll position and re-apply it on page load (as you've done with scroll).

It will be something like this :

const boxLocalStorageId = "boxTop";

function saveButtonPosition(boxTop) {
  localStorage.setItem(boxLocalStorageId, boxTop);
}

function loadButtonPosition() {
  if(localStorage.hasOwnProperty(boxLocalStorageId)) {
    // We have found button position in local storage
    return localStorage[boxLocalStorageId];
  } else {
    // We didn't found the data -> we return a default value
    return 0;
  }
}

You'll then need to call saveButtonPosition on save button click

And for the loadButtonPosition, you could add after your confirm boxMove.style.top = loadButtonPosition() "px";

CodePudding user response:

You should add an event on the scroll of the body element and in the handler function record document.scrollingElement.scrollTop value in the cookie or local storage. On loading page handler you can load data from you storage location and use document.scrollingElement.scrollTo({top: value}) to scroll page to last position.

  • Related