Skip to content

Instantly share code, notes, and snippets.

@dashkevych
Last active March 7, 2023 20:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dashkevych/7c92d92f88aaa56f13bc99f7c92b7d78 to your computer and use it in GitHub Desktop.
Save dashkevych/7c92d92f88aaa56f13bc99f7c92b7d78 to your computer and use it in GitHub Desktop.
Creating "Back to Top" button in WordPress.
jQuery( document ).ready(function($){
var offset = 100,
speed = 250,
duration = 500,
scrollButton = $('#topbutton');
$( window ).scroll( function() {
if ( $( this ).scrollTop() < offset) {
scrollButton.fadeOut( duration );
} else {
scrollButton.fadeIn( duration );
}
});
scrollButton.on( 'click', function(e){
e.preventDefault();
$( 'html, body' ).animate({
scrollTop: 0
}, speed);
});
});
/**
* Enqueue button javascript script.
*/
function themeslug_add_button_script() {
wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/back-to-top.js', array( 'jquery' ) );
}
add_action( 'wp_enqueue_scripts', 'themeslug_add_button_script' );
/**
* Add button HTML to the footer section.
*/
function themeslug_add_scroll_button() {
echo '<a href="#" id="topbutton"></a>';
}
add_action( 'wp_footer', 'themeslug_add_scroll_button' );
#topbutton {
position: fixed;
display: none;
height: 40px;
width: 40px;
line-height: 40px;
right: 15px;
bottom: 15px;
z-index: 1;
background: #000000;
border-radius: 2px;
text-decoration: none;
color: #ffffff;
text-align: center;
}
#topbutton:after {
content: "\2191";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment