I am using iWeb (horrible but i have to use it, long story).
I have managed to get some smooth scrolling links on a page but i am having trouble getting it to scroll to the correct location.
Here is my code for the "HTML Widget" which is loaded into an iframe (FYI this is the menu):
<html>
<head>
<script type="text/javascript">
// the var's are referneces to iWeb's generated div's have to publish and get id's
var about = "id1";
var products = "id4";
var technical = "id7";
// var contactus = "id14";
$(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', window.parent.document).animate({
//scrollTop: parent.document.getElementById(products).offsetTop // this works but is a static ref
scrollTop: parent.document.getElementById(theTarget).offsetTop
}, 1000);
return false;
}
}
});
});
</script>
</head>
<body>
<div style="width: "100%"; height: "0%"">
<a href="#about" id="about" class="myButton">About</a>
<a href="#products" id="products" class="myButton">Products</a>
<a href="#technical" id="technical" class="myButton">Technical</a>
<a href="#contactus" id="contactus" class="myButton">Contact</a>
</div>
</body>
</html>
Now when i view this an click on a link, it will just load the iframe page instead of scrolling the main window.
But if i comment/uncomment the other ScrollTop line it will work but obviously it will only scroll to the "id4" div in the parent window.
How can i get this to work the way i need it to without copy/pasting the same function over and over for each link?
I suggest sort of a dictionary to map the link hashes to element IDs:
var map = {
'#about': 'id1',
'#products': 'id4',
'#technical': 'id7',
'#contactus': 'id14',
};
This way you can then use target
as a key to that map:
if (target.length && target in map) {
$('html, body', window.parent.document).animate({
scrollTop: parent.document.getElementById(map[target]).offsetTop,
}, 1000);
return false;
}