Reputation: 1832
I have the following function:
function scrollToDiv(){
var str = '.' + window.location.href.split('#').pop();
$.scrollTo(str, {duration: 300});
}
It extracts the test
from www.example.com/#test
and sets str
to .test
. However, the scrollTo() scrolls to the div AFTER <div class="test"></div>
. Why is that?
Update: I've noticed that the offset().top is showing wrong numbers for each div.
Upvotes: 0
Views: 410
Reputation: 2159
This is an unnecessarily complex function. There is a property called window.location.hash
which gets the exact part you want (even though that bit of your code works pretty well). A similar and more effective implementation of your code is:
function scrollToAnchor(place){
var cls = window.location.hash.replace("#", "."),
sel = $(cls + ":eq(" + place + ")");
place++;
$.scrollTo(sel, {duration: 300});
}
I have added a place
argument that scrolls to the given place (indexed by 1 not 0 because I increment the variable to make it easier to understand). Notice I simply replace the hash symbol in the hash
property value with a dot because that's what you need. I hope this has helped you a bit and let me know if you don't understand my changes. Here's a full HTML page using this function:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="https://raw.github.com/flesler/jquery.scrollTo/master/jquery.scrollTo.min.js" type="text/javascript"></script>
<style type="text/css">
#something {
display: block;
margin-top: 800px;
}
</style>
</head>
<body>
<a class="something">Test</a>
<a class="something">Test</a>
<a class="something">Test</a>
<a class="something">Test</a>
<a class="something">Test</a>
<script type="text/javascript">
function scrollToAnchor(place){
var cls = window.location.hash.replace("#", "."),
sel = $(cls + ":eq(" + place + ")");
place++;
$.scrollTo(sel, {duration: 300});
}
scrollToAnchor(3);
</script>
</body>
</html>
Could've done a Fiddle or a CodePen project but you need to pass something as the hash (obviously) and that's a bit strange to try and mock up with editors like those. Just pass #something
to that HTML file and it will do what you're seeking.
Upvotes: 1
Reputation: 5126
The scroll to behaviour is normally executed on IDs by default by browsers. Hence, when you click on any link like http://example.com/#test , any decent browser will scroll to element which has id - test. Try using ids instead of classes.
Upvotes: 0