Reputation: 277
I am looking for a way to scroll from <div id="myButton">Home</div>
to the centre of another div point . The aim of this is because I have 4 pages and I want them to be horizontally next to each other with a navigation bar (which stays perfectly in the centre) that follows the pages.
Why is this not working?
Here is a JSfiddle
$('div#myButton').click(function () {
$.scrollTo($('div#myDiv'), 500);
});
I have:
<body>
<div id="myButton">yo</div>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
.....
<p> </p>
<p> </p>
<div id="myDiv">hello</div>
<script>
$("div#myButton").click(function() {
$('html, body').animate({
scrollTop: $("div#myDiv").offset().top }, 2000);
});
</script>
</body>
But it is still not working?!!
Upvotes: 0
Views: 3959
Reputation: 100381
You can use scrollTop
to scroll. otherDiv.offset().top
will place you at the top of the div and adding otherDiv.height() / 2
will scroll down to the center of the div
$('div#myButton').click(function () {
var otherDiv = $('div#myDiv');
$("html, body").scrollTop(otherDiv.offset().top + otherDiv.height() / 2);
});
Example on jsFiddle, the top of your page will be exactly on the center of the div
Upvotes: 0
Reputation:
Here's a fiddle with the plugin in the 'external resources': http://jsfiddle.net/LKu6p/1/
Your code is right, the plugin isn't loading for some reason. Check the <head>
area of the code to check that it's there and if it is, whether the path to the file is correct.
However, I agree with Royi - if you can do this without a plugin, all the better.
Upvotes: 0
Reputation: 19557
This is a javascript function, not a jquery function, and is the same as window.scroll.
window.scrollTo( x-coord, y-coord )
x-coord is the pixel along the horizontal axis of the document that you want displayed in the upper left.
y-coord is the pixel along the vertical axis of the document that you want displayed in the upper left.
Source: https://developer.mozilla.org/en-US/docs/Web/API/window.scrollTo
Upvotes: 0
Reputation: 148744
You can do it without plugin.
Just a small change in plan .
$("div#myButton").click(function() {
$('html, body').animate({
scrollTop: $("div#myDiv").offset().top }, 2000);
});
Upvotes: 2