Scroll to element in jQuery
In this tutorial we will show you how to allow users scroll to specified element by clicking a links using jquery. Scroll to specific element (generally paragraphs or different sections) may be required for long content pages in your website. jQuery also provides scroll method, however to make scroll smooth we will use jquery animate method for our jquery scroll to element example.
A scroll to element example
In Example below jQuery animate() method is used to scroll to specified element. As “Move Middle” link is clicked the page will be scrolled to middle. Example below uses test text just to ensure scroll bars are there.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
<html>
<head>
<script src=“http://code.jquery.com/jquery-1.10.1.min.js”></script>
<script>
$(document).ready(function(){
$(“#scrollbottom”).click(function() {
$(‘html, body’).animate({scrollTop: $(“#moveMiddle”).offset().top }, 2000);
});
$(“#movetop”).click(function() {
$(“html, body”).animate({ scrollTop: 0 }, 2000);
});
});
</script>
</head>
<body>
<a href=“#” id=“scrollbottom”>Scroll to Middle</a>
<p>Text to bring scroll bars! Text to bring scroll bars! Text to bring scroll bars! Text to bring scroll bars! <br /><br />
Text to bring scroll bars! Text to bring scroll bars! Text to bring scroll bars! Text to bring scroll bars! <br /><br />
</p>
<a href=“#mid” id=“moveMiddle”>Middle</a>
<p>
Text to bring scroll bars! Text to bring scroll bars! Text to bring scroll bars! Text to bring scroll bars! <br /><br />
Text to bring scroll bars! Text to bring scroll bars! Text to bring scroll bars! Text to bring scroll bars! <br /><br />
</p>
<a href=“#top” id=“movetop”>Move top</a>
</body>
</html>
|
Leave A Comment?