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>
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>