Last active
March 7, 2023 20:30
-
-
Save dashkevych/7c92d92f88aaa56f13bc99f7c92b7d78 to your computer and use it in GitHub Desktop.
Creating "Back to Top" button in WordPress.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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' ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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