Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - maintain scroll position on post

I have simple commenting system in my Laravel app. Problem is when someone submits a comment page is reloading on top of the page. I would like that page returns user on the same position where original comment is made (maintain scroll position).

Here is part of a view responsible for comments:

@if ($signedIn)

    {{ Form::open(['route' => ['comment_path', $status->id], 'class' => 'comments__create-form',]) }}
    {{ Form::hidden('status_id', $status->id) }}

<div class="form-group">

    {{ Form::textarea('body', null, ['class' => 'form-control', 'rows' => 1]) }}

</div>

    {{ Form::close() }}

@endif

@unless ($status->comments->isEmpty())

<div class="comments">

@foreach ($status->comments as $comment)

@include ('statuses.partials.comment')

@endforeach

</div>

@endunless

Here is jquery script that submits a comment when someone hits ENTER

<script>

$('#flash-overlay-modal').modal();

$('.comments__create-form').on('keydown', function(e) {

    if (e.keyCode == 13) {

        e.preventDefault();
        $(this).submit();
    }

});

</script>

Thank you for your help!

like image 852
Goran Avatar asked Sep 03 '25 01:09

Goran


1 Answers

ok, I tried probably all solutions available and non of them worked perfectly when you have a lot of forms on a page like I have.

Thank to Evalds Urtan I solved the problem. Evalds have the best and shortest script for maintaining scroll position.

And you don't have to do anything, just include his jquery

/*
* Maintain / Keep scroll position after post-back / postback / refresh. Just include plugin (no need for cookies)
*
* Author: Evalds Urtans
* Website: http://www.evalds.lv
*/
(function($){
window.onbeforeunload = function(e){    
window.name += ' [' + $(window).scrollTop().toString() + '[' + $(window).scrollLeft().toString();
};
$.maintainscroll = function() {
if(window.name.indexOf('[') > 0)
{
var parts = window.name.split('['); 
window.name = $.trim(parts[0]);
window.scrollTo(parseInt(parts[parts.length - 1]), parseInt(parts[parts.length - 2]));
}   
};  
$.maintainscroll();
})(jQuery);

Thank you Evalds!

like image 122
Goran Avatar answered Sep 04 '25 14:09

Goran