Introduction
This Tip is useful when user scrolls down a long web page and wants to go to the top of the web page with one-click .
It can be done with help of JavaScript,
so here we begin.
Background
You should have little bit knowledge of CSS, JavaScript.
Don't worry if you don't understand just copy & paste as described and it will work without any problem
Using the code
For Web Page
Here I used anchor tag, i.e., <a>↑</a> , you can use upside arrow by pressing the key Alt+2+4 and release same time and you will get upside arrow ↑
So after using anchor tag in your web page , here is code which will like this
<a id="top" > ↑ </a>
I have given a id to anchor tag, so that it pointed by CSS and JavaScript.
You can place the anchor tag wherever in web page but it should in between
<body>
</body>
CSS
Now we have to use css to position the anchor tag at right place in our web page.
In your css file we have to use the code written below
#top{
text-align:center;
width:10px;
border:1px dashed #111111;
color:#111111;
position:fixed;
top:90%;
right:3%;
cursor:crosshair;
padding:2px 4px;
border-radius:2px 10px 2px 10px;
}
#top:hover{
background-color:#111111;
color:#e4e5e5;
}
The code above will position your anchor tag 90% from top and spacing 3% from right side of page.
So when window screen size changes , it will automatically changes its position according to screen size and position in right place .
You can place your anchor tag either on top of all tag in your web page before header or below the footer. It doesn't matter at all .
JavaScript / jQuery
Now lets write less and do more with jQuery. Here
I make a function named scroll()
. Note: text written after // are comments to explain code .
$(document).ready(function ()
{
scroll();
});
function scroll()
{
$("#top").hide();
$(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 100)
{
$('#top').fadeIn();
} else {
$('#top').fadeOut();
}
});
$('#top').click(function () {
$('body,html').animate({
scrollTop: 0
}, 800);
return false;
});
});
}
You can use this in custom javascript file , so that it can be used anywhere in your project .
Or in your web page where it required.
You
have to include one jQuery file, you can download it from here http://code.jquery.com/jquery-1.10.2.min.js.
After doing all this, your HTML page will look like this:
<html>
<head>
<title>JavaScript Scroll </title>
<link href="~/Content/Site.css" rel="stylesheet" />
<script src="../Scripts/jquery1.10.2.js"></script> - the file you have download and include in you project
<script src="../Scripts/Custom.js"></script> - this is your custom JavaScript File.
</head>
<body>
<a>↑</a>
</body>
</html>
So we are done.
If you face any problems, comment below.