hankknight
asked on
jQuery: Scroll paragraph contents to specific element
Using jQuery, I want to scroll the contents of a paragraph so that a specific element is at the top.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo</title>
<style type="text/css">
h1 {
text-align: center;
}
div p {
margin: 40px auto 0 auto;
width: 300px;
height: 200px;
overflow: auto;
border: 2px solid #333;
}
a {
color: blue;
cursor: pointer;
text-decoration: underline;
display: block;
font-size: 15px;
line-height: 22px;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#goto3').click(function() {
alert('Scroll the contents of the box so that "Hello 3" is at the top of the box.');
});
});
</script>
</head>
<body>
<h1>Hello</h1>
<div>
<p>
<a id="hello1">Hello 1</a> Test
<a id="hello2">Hello 2</a> Test
<a id="hello3">Hello 3</a> Test
<a id="hello4">Hello 4</a> Test
<a id="hello5">Hello 5</a> Test
<a id="hello6">Hello 6</a> Test
<a id="hello7">Hello 7</a> Test
<a id="hello8">Hello 8</a> Test
<a id="hello9">Hello 9</a> Test
</p>
</div>
<p><a id="goto3">Show "Hello 3" at top of box</a></p>
</body>
</html>
ASKER
Thanks, Roonaan, but I do not think you understand what I need to do. Have you tested the code I posted? I don't want to scroll the page. I want to scroll a paragraph inside the page. If you test the code I posted, you will see what I need.
Hank, you can use this: (The "prop" method was added in jQuery 1.6. If you really need to make this compatible with 1.5.x, use the "attr" method instead.)
$('#goto3').click(function() {
var el=$('#hello3'),
pOffset=el.parent().offset().top-el.parent().prop('scrollTop');
el.parent().animate({scrollTop:el.offset().top-pOffset});
});
However, I'd probably give "position:relative" to "div p" and use this: $('#goto3').click(function() {
var el=$('#hello3');
el.parent().animate({scrollTop:el.position().top});
});
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks. Must I use animate for this? I want it to happen instantly without an animation.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
http://www.solidpitch.com/2009/03/31/jquery-scrollintoview-in-one-line/
Open in new window