Implemented scroll to top using stimulus.

This commit is contained in:
Jan Böhmer 2022-07-30 00:47:51 +02:00
parent 8ccf5652ab
commit 1f890efc97
3 changed files with 30 additions and 27 deletions

View file

@ -0,0 +1,27 @@
import {Controller} from "@hotwired/stimulus";
import {Tooltip} from "bootstrap";
export default class extends Controller {
connect() {
window.addEventListener('scroll', this._onscroll.bind(this));
}
_onscroll() {
const button = this.element;
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
button.style.display = "block";
} else {
button.style.display = "none";
}
}
backToTop() {
//Hide button tooltip to prevent ugly tooltip on scroll
Tooltip.getInstance(this.element)?.hide();
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
}

View file

@ -7,13 +7,9 @@ import "bootstrap-fileinput/css/fileinput.css"
import "bootstrap-fileinput"; import "bootstrap-fileinput";
import {Popover} from "bootstrap";
class RegisterEventHelper { class RegisterEventHelper {
constructor() { constructor() {
this.registerTooltips(); this.registerTooltips();
this.registerJumpToTopBtn();
this.registerFileInput(); this.registerFileInput();
this.registerSpecialCharInput(); this.registerSpecialCharInput();
@ -39,26 +35,6 @@ class RegisterEventHelper {
}); });
} }
registerJumpToTopBtn() {
this.registerLoadHandler(() => {
$(window).scroll(function () {
if ($(this).scrollTop() > 50) {
$('#back-to-top').fadeIn();
} else {
$('#back-to-top').fadeOut();
}
});
// scroll body to 0px on click
$('#back-to-top').click(function () {
$('#back-to-top').tooltip('hide');
$('body,html').animate({
scrollTop: 0
}, 800);
return false;
}).tooltip();
});
}
registerSpecialCharInput() { registerSpecialCharInput() {
this.registerLoadHandler(() => { this.registerLoadHandler(() => {
//@ts-ignore //@ts-ignore

View file

@ -107,10 +107,10 @@
{# Back to top buton #} {# Back to top buton #}
<!-- Back to top button --> <!-- Back to top button -->
<a id="back-to-top" href="#" class="btn btn-primary back-to-top" role="button" <button id="back-to-top" class="btn btn-primary back-to-top" role="button" title="{% trans %}back_to_top{% endtrans %}"
title="{% trans %}back_to_top{% endtrans %}" data-bs-toggle="tooltip" data-placement="left"> {{ stimulus_controller('common/back_to_top') }} {{ stimulus_action('common/back_to_top', 'backToTop') }}>
<i class="fas fa-angle-up fa-fw"></i> <i class="fas fa-angle-up fa-fw"></i>
</a> </button>
{% endblock %} {% endblock %}