Go Up button for WordPress

Categories: Wordpress, CMS

Create a Javascript in the theme/js directory called back-to-top.js:

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);
});
});

Add to functions.php of the theme:

/**
* 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' );

Add to custom CSS:

#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";
}

References: https://gist.github.com/dashkevych/7c92d92f88aaa56f13bc99f7c92b7d78

«
»