Archived topic
Running Smooth Scroll script in functionality plugin
5 replies · Started by Max on October 29, 2017
Tom
I got your smooth scroll script from another thread (displayed below).
Works fine in GP footer hook. However I want to run the script in my functionality plugin rather than in the footer hook.
Can you please let me know how to do this.
Kind Regards
Max
<script>
jQuery(function($) {
$(document).on('click', 'a[href*="#"]:not([href="#"])', function(e) {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
e.preventDefault();
$('html,body').animate({
scrollTop: target.offset().top
}, 500);
}
}
});
});
</script>
Hi there,
What's your functionality plugin? Like your own plugin?
Yes, I have my own plugin that I use to run various snippets. That is why I want to add Tom's script to my plugin rather than having in the footer hook.
Kind Regards
Max
You could do this:
add_action( 'wp_footer', 'tu_add_script' );
function tu_add_script() { ?>
Your script in here
<?php }
Thanks Tom
For anyone who is interested in this thread, here is the full snippet to run smooth scroll from your own functionality plugin:
Note: this only works to smooth scroll to an anchor on the same page. It does not work if your anchor is on another page.
//////////////////// GP SMOOTH SCROLL ////////////////////////////////
add_action( 'wp_footer', 'tu_add_script' );
function tu_add_script() { ?>
<script>
jQuery(function($) {
$(document).on('click', 'a[href*="#"]:not([href="#"])', function(e) {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
e.preventDefault();
$('html,body').animate({
scrollTop: target.offset().top
}, 500);
}
}
});
});
</script>
<?php }
//////////////////// END GP SMOOTH SCROLL ///////////////////////////////
Kind Regards
Max
Thanks for sharing, Max! :)