Javascript Browser Location href Property point to an anchor within a page

Introduction

Set the href value to point to an anchor within a page:

location.href = "#top";

View in separate window

<!DOCTYPE html>
<html>
<body>

<h2><a id="top">There is a link at the bottom of the page!</a></h2>

<p>This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. </p>
<p>This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. </p>
<p>This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. </p>
<p>This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. </p>
<p>This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. </p>

<button onclick="myFunction()">Go to top</button>

<script>
function myFunction() {/* w ww  .  jav  a2 s.  co m*/
  location.href = "#top";
}
</script>

</body>
</html>



PreviousNext

Related