views:

24

answers:

2
$(window).scroll(function() {
    $('#myElement').css('top', $(this).scrollTop() + "px");
});

works great, but what if I want it fixed to the bottom instead of top?

Many thanks

+1  A: 

You could do it by adding the element's height to the scrollTop value:

$(window).scroll(function() {
    var myElement = $('#myElement');
    myElement.css('top', $(this).scrollTop() + $(this).height() - myElement.height() + "px");
});

Alternatively, have you looked into using position: fixed? It works well in all browsers except IE, and you can get around it with CSS expressions.

Pat
This would put the element off the screen :) You need to subtract the element's height to have it back in the view port.
Nick Craver
@Nick much obliged - example updated. Out of curiosity, is it worth assigning `$('#myElement')` to a variable rather than doing the DOM lookup twice or are the jQuery lookups fast enough to make this a case of unnecessary optimization?
Pat
+1  A: 

Here's my code & try out the demo : http://jsbin.com/aguca3

HTML :

<!DOCTYPE html>
<html>
<head>
  <style type="text/css">
    #scrollDown {
      color : #0099f9;
      border:5px solid #2f2f2f;
      background:#d5d5d5;
      -moz-border-radius:5px;
      -webkit-border-radius:5px;
      border-radius:5px;
      position:fixed;
      top:30px;
      right:30px;
      font:bold 14px Verdana;
      padding:5px;
      cursor:pointer;
    }
    #scrollDown:hover {
      color:#fcfcfc;
      background:#000;
      border-color:#0099f9;
    }




  </style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
<meta charset=utf-8 />
<title>Change text</title>

</head>
<body>
  <div id="scrollDown" > Scroll Down </div>


<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> 

<span style="float:right;"> you have Reached the End of page</span>
</body>
</html>

Javascript :

$(document).ready(function() {
  $('#scrollDown').click(function() {
    var height = $('html,body').height();
    $('html,body').stop().animate({scrollTop: height},2000);
  });
});
Ninja Dude