Usar jQuery para almacenar la posición de desplazamiento funciona bien. ¿Cómo permito SOLAMENTE solicitudes de actualización, no de página nueva?

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 después de 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?

EDITAR -

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>

preguntado el 21 de septiembre de 13 a las 00:09

Why not set the cookie only on submit instead? You could then get rid of it after you scroll. -

I will see if I can make that work. -

@Meximize - I tried a few things, see my edit for the newest code... it doesn't work at all now. -

1 Respuestas

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>

Respondido el 21 de Septiembre de 13 a las 01:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.