Reputation: 55
So i got some custom created pages on wordpress + and main index template which is my main page.I want to add scroll to top button on all pages.When i add code to main index page it shows only on home page and when i add it to page template file it appears only on posts pages.So is there a way to make code acting on both pages ( i got like 4 more custom pages,just giving example with 2) without copying of the code on each file?Because if i make even more custom pages it will be a lot of code copied and i definetlly don't want that. Thanks :P
Upvotes: 3
Views: 4368
Reputation: 3816
footer.php
and header.php
is used by all pages (normaly). You can put such code in there.
The best way to implement a "scroll to top button" is IMO via javascript. The javascript code can check if a "scroll to top button" is suitable, because you don't need it when the content is not to big, or if you actualy on top. And when you scroll down a certain distance, it appears at a fixed position.
var scroll_top_button_is_visible = false;
var scroll_distance = 500;
var $scroll_top_button = $('<div class="scroll-top-button">back to top</div>');
// inject the button, so you don't have to create the button in any templates
$scroll_top_button.appendTo('body');
$(window).scroll(function() {
// called on every scroll action
if ($(window).scrollTop() > scroll_distance && !scroll_top_button_is_visible) {
scroll_top_button_is_visible = true;
$scroll_top_button.fadeIn(200);
} else if ($(window).scrollTop() < scroll_distance && scroll_top_button_is_visible) {
scroll_top_button_is_visible = false;
$scroll_top_button.fadeOut(200);
}
});
// scroll to top if button is clicked
$('.scroll-top-button').click(function() {
$("html, body").animate({
scrollTop: 0
}, "slow");
});
p {
margin-bottom: 300px;
}
.scroll-top-button {
display: none;
position: fixed;
bottom: 10px;
right: 10px;
padding: 5px;
color: white;
background: red;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="page">
<h1>Example of a "Scroll to Top Button"</h1>
<h2>Scroll down and look what happens</h2>
<p>Some content</p>
<p>Some content</p>
<p>Some content</p>
<p>Some content</p>
<p>Some content</p>
<p>Some content</p>
<p>Some content</p>
<p>Some content</p>
<p>Some content</p>
<p>Some content</p>
</div>
Upvotes: 1
Reputation: 9121
create a shortcode for the button with scroll and add the shortcode in all pages' front end
Upvotes: 1