How to make custom JS persist
-
Hi all. I've put together some simple JS and CSS that presents a scroll to top function when the forum loads. However, navigating to subsequent pages means that the JS no longer triggers. I suspect that this is because the forum is an SPA, but wanted to know what I could do to have the JS fire everywhere.
Would this be better as a plugin ?
Thanks
-
Do you mind sharing the code you're using? A simple function like that should be able to persist across pages.
-
@phenomlab use ajaxify end instead of document ready.
Document ready is only fired on a hard page load.
Ajaxify is fired on hard page load as well when navigating between pages after first visit / hard reload.
$(window).on('action:ajaxify.end', function(data) { // it's fired everytime });
-
@dogs this worked a treat - thanks. For anyone else who might be looking for something similar, here's a simple scroll to top function that you can place into your Custom JS
// Scroll to top button $(window).on('action:ajaxify.end', function(data) { var btn = $('#btt'); $(window).scroll(function() { if ($(window).scrollTop() > 300) { btn.addClass('show'); } else { btn.removeClass('show'); } }); btn.on('click', function(e) { e.preventDefault(); $('html, body').animate({scrollTop:0}, '300'); }); })
Then place this into your Custom Header
<a id="btt"><i class="fas fa-chevron-up"></i></a>
Obviously, you would need to provide some CSS to style this. An example of this can be found on https://phenomlab.com