Scroll to anchor point onclick final part

Published on : April 27, 2026

Author:

Category: Javascript


In my last tutorial I describe a process to scroll to anchor point. In this tutorial I am giving another process to scroll to anchor point onclick.

Here is our Html file.

[sourcecode]
<html>
<head>
<title>Scroll to anchor point</title>
<link rel="stylesheet" type="text/css" href="style2.css">
<script type="text/javascript" src="jquery-1.10.2.js"></script>
<script>
$(function() {
$(‘a[href*=#]:not([href=#])’).click(function() {
if (location.pathname.replace(/^//,”) == this.pathname.replace(/^//,”) && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $(‘[name=’ + this.hash.slice(1) +’]’);
if (target.length) {
$(‘html,body’).animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
</script>
</head>
<body>
<a href="#red">red</a> <a href="#blue">blue</a>
<div class="section red" id="red"></div>
<div class="section blue" id="blue"></div>
<div class="section green"></div>
</body>
</html>
[/sourcecode]

And here is our Css file.

[sourcecode]
.section{height:550px;}
.red{background-color:#F00;}
.blue{background-color:#036;}
.green{background-color:green;}
[/sourcecode]

And this is simple javascript function to scroll to anchor point when you click on link.

[sourcecode]
<script>
$(function() {
$(‘a[href*=#]:not([href=#])’).click(function() {
if (location.pathname.replace(/^//,”) == this.pathname.replace(/^//,”) && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $(‘[name=’ + this.hash.slice(1) +’]’);
if (target.length) {
$(‘html,body’).animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
</script>
[/sourcecode]