Paddy Hallihan
Paddy Hallihan

Reputation: 1686

Go to top of page

I created an icon at the side of my page that can be clicked to go back to the top of the page.

I thought this would be fairly simple, like so:

#back_to_top{
	position:fixed;
	right:0px;
	bottom:80px;
	padding:10px;
	background-color:#fff;
	opacity:0.5;
	border-radius:10px 0px 0px 10px;
	cursor:pointer;
}
#back_to_top img{
	width:50px;
	height:50px;
}
#content{
  height:9999px;
}
<a id="top_of_page"></a>

<div id="content">loads of content</div>

<div id="back_to_top">
	<a href="#top_of_page">
	<img src="media/top.png">
	</a>
</div>

However, when I click the icon it actually moves down the page by the same amount of pixels each time.

I know its working in the snippet but I can't share a full example, however, any ideas why this might act this way, would be really appreciated.

Upvotes: 2

Views: 3758

Answers (3)

user5224681
user5224681

Reputation: 41

Depending on whether you want to use a link tag <a> or a <button> tag you have two simple approaches.

For a link tag:

<a href='#'>To Top</a>

is all you need.

For a button tag:

<button onclick="window.scrollTo(0,0)>To Top</button>

Both of these work well.

Upvotes: 0

Animan
Animan

Reputation: 312

I prefer to use the Javascript window.scrollTo method. Passing in 0,0 will scroll the page to the top left corner instantly.

Syntax: window.scrollTo(x-coord, y-coord)

x-coord - Pixels along horizontal axis

y-coord - Pixels along vertical axis

This method allows you to scroll to any point on the page.

Upvotes: 3

Alvaro Castro
Alvaro Castro

Reputation: 841

Adding an a element with href="#" should do the trick.

Here you have an example of it working:

<h1>MOON</h1>
<div style="height: 700px;"><small>scroll down</small></div>
<a href="#">To the moon!</a>

Upvotes: 6

Related Questions