Creating a good user experience on your website is very important to keep people on the page. The best way to create a good user experience is to make it easy for people to use, if your site is difficult to use it annoys people and they will move on. For websites that have a lot of information on the page you will scroll far down the page to consume the information. Websites like Google+ who have infinite page scroll can be very annoying if you want to go back to the top of the page to click on a link there. You can either refresh the page or move the scroll bar all the way back to the top. Websites with initiate scroll need something to make it easy to return to the top. This is done with a button which will scroll them back to the top. In this tutorial you will learn how you can create an animated scroll to top button with jQuery. Demo
The Button
First lets create the button.
<a href="#" class="scrollToTop">Scroll To Top</a>
Now we can style the button with the following CSS.
.scrollToTop{ width:100px; height:130px; padding:10px; text-align:center; background: whiteSmoke; font-weight: bold; color: #444; text-decoration: none; position:fixed; top:75px; right:40px; display:none; background: url('arrow_up.png') no-repeat 0px 20px; } .scrollToTop:hover{ text-decoration:none; }
This will position the scroll to top button at the top right of the page which we have fixed to stay in this position. As you can see from the CSS we have set the display to be none so it will be hidden in the browser, you will see why we do this in the jQuery code.
jQuery Part
Below is the jQuery part of this functionality, we will add a action on the scroll event to make the button appear when not at the top of the window and then make the button disappear when we are at the top of the page. We will then need to create a click event on the button to scroll to the top of the window. Copy and paste the following in the Javascript file to add the Javascript functionality.
$(document).ready(function(){ //Check to see if the window is top if not then display button $(window).scroll(function(){ if ($(this).scrollTop() > 100) { $('.scrollToTop').fadeIn(); } else { $('.scrollToTop').fadeOut(); } }); //Click event to scroll to top $('.scrollToTop').click(function(){ $('html, body').animate({scrollTop : 0},800); return false; }); });
This uses the scroll function which is ran when the visitor scrolls the window. We can then work out the position of the window by using the scrollTop function, if the position is move than 100 then we want to display the button. We display the button by using the fadeIn function to add the first bit of animation to the screen. If the scrollTop is less than 100 then we know that the window is near the top so we don’t need to display the button. Now we can add a click event to the scroll to top button. On the click action of this button we want to scroll the page back to the top n animation by using the animate function. To scroll back to the top of the window we need to change scrollTop property to 0. That’s all you need to recreate this very useful feature, view the demo to see what it will create. Demo
Add This To A WordPress Site
To use this in a WordPress site you can download the WordPress plugin to add a back to top link to your site. Back To Top WordPress Plugin
Not Using jQuery?
If you don’t want to install the dependency of jQuery on your website then you can do the above using pure JavaScript. Follow the link below to discover how to do this without jQuery. Back To Top Pure JavaScript
paulund.co.uk

This is a short tutorial on how to put a button on your web site that when clicked, will take the visitor to the top of the page in a smooth animation.
You can see how the button works by looking at the right side of my site. There should be a button there. If there isn’t a button there, scroll down a bit and it should appear. Try clicking on it ?
I’ve also made a simple demo page. You can download the demo here.
Step 1
Let’s start by adding jQuery to a page. You do that by pasting this code into the head tag of your html document.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
This will tell the browser to load jQuery from Googles server when your page is loaded.
Step 2
Add this html code to the bottom of your html, just before the body tag closes.
<a id="toTop" href="#">Go to Top</a>
This is the button/link that will take the user to the top when clicked.
Step 3
Now we’ll add some CSS for the button. It should also go into your head tag. We want the button to be located to the right and positioned in the vertical center of the page.
<style type="text/css"> #toTop { display: block; position: fixed; top: 50%; right: 0; padding: 10px; border: 2px solid red; background: white; } </style>
By using position: fixed; When the user scrolls, the button will always appear at the same place on the page.
Step 4
Now we’ll add script tags and initate jQuery.
<script> $(document).ready(function(){ // Javascript code will go here. }); </script>
The second line “$(document).ready(function()” will tell the browser to run the code inside these brackets when the page loads.
I always test if jQuery is working by typing “alert(“jQuery is working!”);” inside the document.ready function. Like this:
$(document).ready(function(){ // Javascript code will go here. alert("jQuery is working!"); });
If it works, when your refresh your page you should get an alert “jQuery is working!”, if not, you should check if you loaded jQuery correctly.
Step 5
We can finally add the javascript that will make the page automatically scroll up when the button is clicked.
$(document).ready(function(){ // Hide the toTop button when the page loads. $("#toTop").css("display", "none"); // This function runs every time the user scrolls the page. $(window).scroll(function(){ // Check weather the user has scrolled down (if "scrollTop()"" is more than 0) if($(window).scrollTop() > 0){ // If it's more than or equal to 0, show the toTop button. console.log("is more"); $("#toTop").fadeIn("slow"); } else { // If it's less than 0 (at the top), hide the toTop button. console.log("is less"); $("#toTop").fadeOut("slow"); } } }); // When the user clicks the toTop button, we want the page to scroll to the top. $("#toTop").click(function(){ // Disable the default behaviour when a user clicks an empty anchor link. // (The page jumps to the top instead of // animating) event.preventDefault(); // Animate the scrolling motion. $("html, body").animate({ scrollTop:0 },"slow"); });
I hope I have commented the above code so you will understand what is happening. The demo html file also has comments in it to make it easier to understand. If something is not working properly or you think this is the best tutorial that’s ever been written, don’t hesitate to comment ?
adriantomic.se
Providing a good user experience is the primary concern of a web designer. You may have visited web pages with many scrollable pages and going back to top of such web pages is a tedious task for the users. You can add a scroll to top button to your web page, if you want to offer a good user experience.
In this post, we are going to discuss how to create a scroll to top animation in jQuery that will allow the users to easily scroll to top of the page with a single click.
I recommend you to go through the following tutorials before proceeding to this one.
- jQuery Scroll Event
- jQuery Fade In and Fade Out effects
- jQuery animate()
You can use the following code to implement the scroll to top functionality with animation.
Copy<!doctype html> <html> <head> <title>jQuery Scroll To Top</title> <style> .scroll_To_Top{ width:150px; height:100px; color: black; text-decoration: none; position:fixed; padding:10px; text-align:center; background: white; font-weight: bold; top:100px; right:50px; display:none; } .scroll_To_Top:hover{ text-decoration:none; color:green; } </style> <sc.
oll To Top Demo</h2> <!-- Your contents goes here. --> <p> <a href="#" class="scroll_To_Top">Scroll To Top <span><!-- Image goes here. --></span></a> </p> </div> </body> </html>
In this example, you can see how we created a scroll to top animation in jQuery. We have used jQuery scroll()
, animate()
, fadeIn()
and fadeOut()
function to animate the scroll to top animation technique.
First we add the following html link in the body
that works as the scroll to top link in our web page.
Copy<a href="#" class="scroll_To_Top">Scroll To Top <span><!-- Image goes here. --></span></a>
You can attach an image to this link to make it attractive. We have added CSS classes to animate the scroll to top link. At first, we are not showing this link.
The following script shows how scroll to top animations works in jQuery.
Copy<script> $(document).ready(function(){ $(window).scroll(function(){ if ($(this).scrollTop() > 100){ $('.scrollToTop').fadeIn(); } else{ $('.scrollToTop').fadeOut(); } }); $('.scrollToTop').click(function(){ $("html, body").animate({scrollTop : 0},700); return false; }); }); </script>
jQuery scroll() method triggers when the window is scrolled . When the scroll event is fired or when we scroll down, we check if the current position of the scroll bar is greater than 100 then scroll to top is displayed else the link will be hidden. We animate this with jQuery fadeIn() and fadeOut() methods.
$("html, body").animate({scrollTop : 0},700);
: Clicking the link will trigger the animate() method,which takes the parameters, scrollTop and the duration of this effect (700 milliSeconds).The scrollTop() method is used to get the current position of the scroll bar and the integer value 0 is the position where you reach on clicking the link. We set the duration of the effect as 700 milliSeconds. You can increase or decrease this value to vary the speed of the animation.
This is how we implement scroll to top animation in jQuery. Hope you all understood the technique. You can see it in action by visiting jQuery Scroll To Top Demo page.
That’s all for now and you will see more jQuery effects, animations and jQuery plugins related articles in the coming posts.
cdn.journaldev.com
Tweet
Some time ago I wrote an article where we discussed how to use JavaScript to create a smooth scroll to the top of the page.
Today we are going to see how to do it with jQuery, and we are going to do it in order to scroll to the top of the page and even to the bottom of the page. After that we are going to create a simple jQuery function that will scroll to a specific element of the page.
Interested? Ok… follow me.
Top and Bottom
The code is very simple. First of all, include the jQuery library in the head of your document (this is valid for the second example as well):
<script type="text/javascript" src="yourPath/jquery.min.js"></script>
After that, we create two links: one for the scroll-to-top, and one for the scroll-to-bottom. Remember to place them where you need them!
<a href="javascript:scrollToBottom()">Bottom</a>
<a href="javascript:scrollToTop()">Top</a>
Now, again in the head of your document the jQuery script:
<script type="text/javascript">
function scrollToBottom() {
$('html, body').animate({scrollTop:$(document).height()}, 'slow');
}
function scrollToTop() {
$('html, body').animate({scrollTop:0}, 'slow');
}
</script>
And we’re done.
Scroll to a specific point
Now… if we need to scroll to a specific point on a page, we can create a target element, like a div:
<div class="scrollTarget">We will scroll to here</div>
Now we insert the «void» link where we need the scroll to be triggered by a click:
<a href"javascript:void(0)" onclick="scrollPageTo('.scrollTarget', 15)">Scroll to div</a>
We pass two parameters to the function: the first is our target and the «.» or «#» is needed depending on the type of selector (class or ID) we used (in our case it’s a class so «.»). The second parameter is used to scroll to a position which is just 15 pixels above the target. The second parameter is optional, but it can be used to make the scroll as perfect as we need it.
The function has to be place in the head of our document:
<script type="text/javascript">
function scrollPageTo(myTarget, topPadding) {
if (topPadding == undefined) {
topPadding = 0;
}
var moveTo = $(myTarget).offset().top - topPadding;
$('html, body').stop().animate({
scrollTop: moveTo
}, 1000);
}
</script>
I must say I’ve found the above snippet somewhere a long time ago and I can’t remember where. I’m sure I’ve used it more than once in web pages and I have surely modified it somehow.
In any case, there we are.
Take care and see you next time!
thewebthought.blogspot.com
Подготовка
Для начала, нам понадобиться картинка кнопки наверх. Для этого можете скачать любую стрелочку или нарисовать сами. Сохраните ее под именем arrow.png. Как вы уже догадались, эта картинка и будет нашей кнопкой наверх.
CSS стили кнопки «Наверх»
В header страницы или в отдельном css файле, установим css стили для div блока с id=scroller.
<style> #scroller{ position: fixed; /** позиция кнопки scroll to top **/ bottom: 30px; /** картинка кнопки наверх**/ background: transparent url(arrow.png) no-repeat left top; width: 32px; height: 32px; cursor: pointer; /** скрываем кнопку в начале **/ display:none; } </style>
Как видите, прежде всего мы установили фиксированную позицию блока, вы можете поменять размещение кнопки scroll to top с помощью значения bottom. Далее мы устанавливаем фоном нашу стрелочку, которую подготовили на первом этапе. В конце, скрываем кнопку, чтобы ее не было видно, когда страница только загружена.
JavaScript код кнопки «Наверх»
Как и полагается, мы напишем код скрипта кнопки в секции header.
Для начала подключим библиотеку jQuery, для этого воспользуемся Google CDN. Хотя вы можете подключить из официального сайта jQuery, Microsoft или из своего сервера. Я использую Google CDN, по моему мнению, он работает наиболее быстро.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
Создаем JavaScript функцию после загрузки библиотеки jQuery.
<script> $(document).ready(function(){ $(window).scroll(function () { if ($(this).scrollTop() > 0) { $('#scroller').fadeIn(); } else { $('#scroller').fadeOut(); } }); $('#scroller').click(function () { $('body,html').animate({ scrollTop: 0 }, 400); return false; }); }); </script>
Разберемся в коде немного попозже… В начале мы вызываем функцию по загрузке страницы:
$(document).ready(function(){ });
В первой части функции, мы устанавливаем событие на scroll событие. Когда происходит скроллинг окна значение переменной scrollTop более 0, в это время мы выводим кнопку «Наверх», когда скроллинг не происходит, мы ее прячем.
Во второй части функции, мы цепляем обработчик события click на кнопку scroll to top (наверх), когда она нажата, мы анимируем скроллинг к тегу body. То есть происходит скроллинг в начало страницы.
На этом создание базового кода кнопки «Наверх» завершено!
Доработки Scroll To Top
Надеюсь, у вас есть тысячи идей, как сделать эту кнопку красивее и лучше. Все что вам предстоит сделать – это внести свои коррективы в этот скрипт. Для примера, можете добавить изменение стиля кнопки при наведении мыши.
sitear.ru
Как сделать кнопку scroll to top на jQuery
Для начала, определимся, что мы хотим сделать: наша кнопка должна появляться на странице, когда мы доскролим до определенной высоты, а сама анимация должна быть плавной. Пропишите путь к вашей библиотеке jQuery, гугл CDN или физическое расположение на вашем сервере.
В данном примере мы не будем рассматривать подробно CSS кнопки, я уверен вы и так знаете, что блок с фразой «вернуться наверх» или иконкой (что на мой взгляд куда симпатичнее смотрится), должен обязательно иметь position fixed или position absolute.
Рассмотрим сам код нашего файла script.js (который тоже нужно подключить, но только после подключения jQuery):
button-up — класс нашей кнопки, например, можно создать в конце вашего документа div с таким классом. По клику происходит анимация к самому верху страницы, за пол секунды, т.к. в javascript все время указывается в миллисекундах. Для увеличения анимации можно поменять 500 на 1000, но мы даже тут будем экономить ?
return false мы пишем только для того, чтобы отменить событие по умолчанию — клик по ссылке с атрибутом href=»#» не будет переходить по ней (в данном случае переход к id на странице).
Как отобразить кнопку на jQuery при прокрутке страницы
Для решения этой задачи сделаем так, чтобы наша кнопка scroll-to-top была скрыта по умолчанию при загрузке страницы. Ваш HTML код должен быть приблизительно следующим (в этот раз рассмотрим именно пример с тегом a, чтобы убедиться в работе return false):
Пишем в CSS:
При загрузке нашей страницы мы не видим эту кнопку. Добавим событие при скролле:
Добавляем функцию при скролле документа и проверяем какая у нас текущая высота, если она больше 800 пикселей, то убираем класс hidden. Со стилями я думаю вы и сами разберетесь. Можно также добавить анимацию плавного появления этой кнопки при помощи CSS3 или немного изменив нашу функцию:
В данном случае нам и класс не понадобился, а какой способ предпочитаете вы? ?
forwww.com
Note: April 7th, 09′. Adds ability to scroll to an absolute position (from top of page) or specific element on the page instead. Also fixes scroll animation not working in Opera.
Description: If your pages are long winded, it’s a good idea to provide viewers with an easy way to quickly/ automatically scroll back to the top of the page. That’s where this script comes in. It displays a stationary control at the lower right corner of the window that when clicked on gently scrolls the page back up to the top. And instead of always being visible on the user’s screen, the script lets you specify how far down the page the user is at (in pixels) before revealing the control. Nifty!
Note that apart from displaying a stationary control, you can also define arbitrary anchor links on the page with a special href value (ie: #top
) that when clicked activate the script and scrolls the page back to the top.
Demo: Scroll the page down (at least 100 pixels) to see a "Back to Top" control appear at the lower right of the window.
Directions:
Step 1: Simply add the below script to the <HEAD> section of your page:
The above references a.js file plus a sample image: which you should download below (right click, and select "Save As"):
-
scrolltopcontrol.js
-
Important Note: Your page should contain a valid doctype at the very top in order for this script to work as intended.
You can customize a variety of things, such as the amount of time it takes the script to scroll back up to the top, duration of the fade in/out effect for the control, and the number of pixels the user’s scrollbar should be from the top of the page before revealing the control. Inside the .js file, here is the relevant section to modify:
setting: {startline:100, scrollto: 0, scrollduration:1000, fadeduration:[500, 100]},
controlHTML: ‘<img src="up.gif" style="width:24px; height:24px" />’, //HTML for control, which is auto wrapped in DIV w/ ID="topcontrol"
controlattrs: {offsetx:15, offsety:15}, //offset of control relative to right/ bottom of window corner
anchorkeyword: ‘#top’, //Enter href value of HTML anchors on the page that should also act as "Scroll Up" links
For "controlHTML
", you can enter any HTML you wish to be shown as the control, though it should be something simple, such as an <IMG>
, or even just plain text. The setting "anchorkeyword
" lets you enter the href value of HTML anchors on the page (if any) that should be parsed by the script and assigned the "scroll to top" behaviour to. With the above setting, the following HTML anchor on the page would also scroll the page back up to the top:
<a href="#top">Back to Top</a>
Back to Top
Changing the target destination of the "Scroll To Top" Control
By default when you click on the Scroll to Top Control, it scrolls the page back up to the very top. However, you can change that to say, 50 pixels from the very top of the page, or scroll to a specific element on the page instead, such as a header. The setting to change is "scrolltop" inside the .js file:
setting: {startline:100, scrollto: 0, scrollduration:1000, fadeduration:[500, 100]},
Change 0 to either an integer (ie: 50), or the ID of the element you wish the control to scroll to, such as "myheader
", where "myheader
" is an element defined on the page:
<h2 id="myheader">Welcome to Dynamic Drive!</h2>
Ignore the following, which is just some dummy text to stretch the height of the document. Ignore the following, which is just some dummy text to stretch the height of the document.
Ignore the following, which is just some dummy text to stretch the height of the document. Ignore the following, which is just some dummy text to stretch the height of the document.
Ignore the following, which is just some dummy text to stretch the height of the document. Ignore the following, which is just some dummy text to stretch the height of the document.
Ignore the following, which is just some dummy text to stretch the height of the document. Ignore the following, which is just some dummy text to stretch the height of the document.
Ignore the following, which is just some dummy text to stretch the height of the document. Ignore the following, which is just some dummy text to stretch the height of the document.
Ignore the following, which is just some dummy text to stretch the height of the document. Ignore the following, which is just some dummy text to stretch the height of the document.
dynamicdrive.com