Make an element draggable and locally save position so will stay after refresh

I can add an element (such as a rectangle) and allow the user to drag it. However when the page refreshes or reloads it will jump back to its original position. Is it possible to save the new location so when reloading it will stay?

you can use hypes API to get and set a position in conjunction with localeStorage to store and retrieve the data

dragStorage.hype.zip (13.0 KB)
may work :slight_smile: not well tested

4 Likes

Very clever :slight_smile:

:mage:
If anyone is curious about the magic going on here, this runs ‘on scene load’:

const dragStorageKey = "elementPositions";
if (event.type === "HypeSceneLoad") {
  let dragStorageObj = getStorage();
  if (dragStorageObj != false) {
    for (key in dragStorageObj) {
      let el = hypeDocument.getElementById(key);
      if (el) {
        hypeDocument.setElementProperty(el, 'left', dragStorageObj[key]['left']);
        hypeDocument.setElementProperty(el, 'top', dragStorageObj[key]['top']);
      }
    }
  }
} else {
  if (event['hypeGesturePhase'] === hypeDocument.kHypeGesturePhaseEnd) {
    let dragStorageObj = getStorage();
    if (dragStorageObj === false) {
      dragStorageObj = {};
    };
    dragStorageObj[element.id] = {};
    let tmpObj = dragStorageObj[element.id];
    tmpObj["left"] = hypeDocument.getElementProperty(element, 'left');
    tmpObj["top"] = hypeDocument.getElementProperty(element, 'top');
    localStorage.setItem(dragStorageKey, JSON.stringify(dragStorageObj));
  }
}

function getStorage() {
  let dragStorageKeys = localStorage.getItem(dragStorageKey);
  if (dragStorageKeys) {
    return JSON.parse(dragStorageKeys);
  } else {
    return false;
  }
}

@h_classen has set this up so as long as your element has an ID set, its location will be stored.

1 Like

Thank You for this example of using localStorage Hans!
So far in my brief run through all has worked fine.

Brilliant Hans! Thank you very much. My only regret now is not posting here before instead of working out how to do this outside the usability of Hype!

Just what I was trying to achieve. Genius :-):grinning:

1 Like