anmaree
anmaree

Reputation: 657

scrollTop inside div not working

I have a container div with multiple div's sitting on top of each other and I want to be able to click a link and then have my overflow: scroll div to scrollTop to associated div that is inside the container div. What I have is not working.

I tried this:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"   
 type="text/javascript"></script>

 <script type="text/javascript">
$("#container").animate({scrollTop: $("#box-2").position().top},1500);
 </script>

html:

<div id="wrapper">
<div id="top-nav">
    <a href="#box-2">How it Works</a>
    <a href="#box-3">About</a>
    <a href="#">Contact Us</a>
</div>
<div class="container">
<div id="box-1"></div>
<div id="box-2"></div>
<div id="box-3"></div>
<div id="box-4"></div>
<div id="box-5"></div>
</div>
<div>

Upvotes: 2

Views: 2107

Answers (2)

Lolukok
Lolukok

Reputation: 54

try:

$(document).ready(function(){
    $("a").click(function(){
        $("#container").animate({scrollTop: $("#box-2").position().top},1500);
    });
});

It would be clever to use another selecter than "a" because now your "#container" div would move everytime if you click at every single link at the page.

The jQuery plugins "LocalScroll" and "ScrollTo" might be interesting for you.

Update:

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
 <style>
    body {background-color: black; color: white;}
    a { text-decoration: none;}
    a:visited { color: green;}
 </style>
 <script type="text/javascript">
 var link;
 $(document).ready(function(){
    $("a").click(function(){
        link = $(this).attr("href");
        $(".container").animate({scrollTop: $(link).position().top},1500);
    });
 });
    </script>
</head>
<body>
    <div id="top-nav">
    <a href="#box-2">How it Works</a>
    <a href="#box-3">About</a>
    <a href="#box-4">Contact Us</a>
    <a href="#box-5">Box 5</a>
</div>
<div id="wrapper">
<div class="container" style="width: 100%; height: 100%; overflow: hidden">
<div id="box-1" style="background-color: red; width: 100%; height: 400px;"></div>
<div id="box-2" style="background-color: blue; width: 100%; height: 400px;"></div>
<div id="box-3" style="background-color: green; width: 100%; height: 400px;"></div>
<div id="box-4" style="background-color: yellow; width: 100%; height: 400px;"></div>
<div id="box-5" style="background-color: purple; width: 100%; height: 400px;"></div>
</div>
</div>
</body>
</html>

Upvotes: 1

anmaree
anmaree

Reputation: 657

I did this :

 <script type="text/javascript">
 $('.link-1').click(function(){
$(".container").animate({scrollTop: $("#box-2").position().top},1500);
return false;
 });
</script>

Upvotes: 1

Related Questions