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!
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With