user3785931
user3785931

Reputation: 47

best way to save and retrieve window scroll position of window using jquery when submit a form

I am new to jquery. I am using php and jquery to do some task. When I submit a form by clicking image button, I want to get the vertical scroll bar position of the window and save it in the browser. Then I want to retrieve it from window and set the scroll bar position back after page reloaded

$(document).ready(function(){
$("#button").click(function(){
  // get the scroll bar position 
  // save the scroll bar position
});
});


$(document).ready(function(){
   If scroll bar position available{
// retrieve the scroll bar position 
// set  the scroll bar position
}
});

I found some solution where the scroll bar position is passed in a hidden input filed and then they set the position by getting POST variable. I need to do without passing it in a hidden input filed Is it possible? Can you help me on it? Thanks in advance

Upvotes: 0

Views: 1243

Answers (2)

user3785931
user3785931

Reputation: 47

Thank you for your reply. I finally did it using sessionStorage. Here is the code

$(document).ready(function(){
  $(":image").click(function(){
        sessionStorage.scrolly=$(window).scrollTop();
  });

  if (sessionStorage.scrolly) {
        $(window).scrollTop(sessionStorage.scrolly);
        sessionStorage.clear();
  }
});

Upvotes: 1

Ali MasudianPour
Ali MasudianPour

Reputation: 14459

As a suggestion, use JQuery's data():

To save data:

$("#button").data("KEY","VALUE");

To get data:

var key=$("#button").data("KEY");

By data() you can store the scroll position, and get it when it's needed.

Upvotes: 1

Related Questions