Save to localStorage the position to hold it when reloading the page

Asked

Viewed 117 times

1

When the user clicks on a given button the scroll position of an element is changed. I would like this action to be stored in Localstorage, but I do not know... can help me?

Here my script:

$('.btn.parteum').click(function(){ 
      $('#textarea').animate({ scrollLeft: 0 }, 400);
      return false; 
});
$('.btn.parte2').click(function(){ 
      $('#textarea').animate({ scrollLeft: 140 }, 400);
      return false; 
});

example: https://jsfiddle.net/g43rmesL/

1 answer

3


You can add a callback that will be called to the end of the animation:

//recupera o valor salvo ao recarregar a pagina
if(localStorage.getItem('scrollposition')){
     $('#textarea').scrollLeft(localStorage.getItem('scrollposition'));
}

$('.btn.parteum').click(function(){ 
      $('#textarea').animate({ scrollLeft: 0 }, 400, function(){
          localStorage.setItem('scrollposition', 0);
      });
      return false; 
});
$('.btn.parte2').click(function(){ 
      $('#textarea').animate({ scrollLeft: 140 }, 400, function(){
          localStorage.setItem('scrollposition', 140);
      });
      return false; 
});

Working example: https://jsfiddle.net/g43rmesL/1/

http://api.jquery.com/animate/

  • thanks for the answer! here did not work... you tested? or is it that I do not know how to put there?... I put exactly as it is there.

  • Your code in question is insufficient to test. It adds your html to the question I test and having found the error.

  • Here, I did an example in the fiddle: https://jsfiddle.net/g43rmesL/

  • Is saving in the localStorage normally

  • Ué, here when I reload the page does not get in the scroll position of the button 2, back to first

  • Your answer was not very clear... You want that when reload recover this value and repeat the action right, I will edit my answer adding this function

  • now that I’ve really figured it out... I should have said "memorize" and not "store," I’m gonna edit

  • I think perhaps it would be better to say "Save to localStorage the position to hold it when reloading the page" But ok, that’s right now. Take a look

  • Thanks for everything!!!!!

  • Quiet man, see you later.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.