1

I'm using this code I found elsewhere on SO:

// When document is ready...
$(document).ready(function() {

// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
    $(document).scrollTop( $.cookie("scroll") );
}

// When a button is clicked...
$(':submit').on("click", function() {

    // Set a cookie that holds the scroll position.
    $.cookie("scroll", $(document).scrollTop() );

});

});

I have the cookie.js file, and the code works wonderfully. However, I'd like to have it so that this code only executes after a submit... right now, it will move to the last scroll position on every load, which is not what I want.

Obviously I can't clear the cookie on $(document).ready, because the code wouldn't do anything at all, right? Any ideas?

EDIT -

Tried this code, but no dice (now it doesn't work at all):

<script type="text/javascript">

$(document).ready(function() {
$(':submit').on("click", function() {

 $.cookie("scroll", $(document).scrollTop() );

     if ( $.cookie("scroll") !== null) {
         $(document).scrollTop( $.cookie("scroll") );
         $.cookie('scroll', null, { path: '/' });
     }
 });

});
</script>
3
  • 1
    Why not set the cookie only on submit instead? You could then get rid of it after you scroll.
    – Meximize
    Sep 20, 2013 at 23:33
  • I will see if I can make that work.
    – jmd9qs
    Sep 20, 2013 at 23:39
  • @Meximize - I tried a few things, see my edit for the newest code... it doesn't work at all now.
    – jmd9qs
    Sep 21, 2013 at 0:29

1 Answer 1

4

Here's what works for what I am doing:

<script type="text/javascript">
// When document is ready...
$(document).ready(function() {

// If scroll AND location cookie is set, and the location is the same
//scroll to the position saved in the scroll cookie.
if ( $.cookie("scroll") !== null && $.cookie("location") !== null 
           && $.cookie("location") == $(location).attr('href')) {
    $(document).scrollTop( $.cookie("scroll") );
}

// When a button is clicked...
$(':submit').on("click", function() {

// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );

// set a cookie that holds the current location.
$.cookie("location", $(location).attr('href'));


});

});
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.