Jump to content

Recommended Posts

This can be done easily by capturing the window.onscroll event, and setting the DIVs style.top property to the document.body.scrollTop, plus a little extra so that it's not right up against the edge of the window.

 

Whipped this up as a quick example:

 

<script type="text/javascript">
window.onscroll = function() {
    setTimeout("scrollDiv()", 500);
}

function scrollDiv() {
    var el = document.getElementById('scrolling_div');
    el.style.top = (parseInt(document.body.scrollTop) + 10) + 'px';
}
</script>

<style type="text/css">
#scrolling_div {
    width: 150px;
    height: 100px;
    position: absolute;
    top: 10px;
    right: 10px;
    border: 1px solid #999;
}
</style>

<div id="scrolling_div">foo</div>

<div style="height: 1500px;">...</div>

 

All the properties and methods used are widely support, so you shouldn't run into any cross-browser issues. Can't guarantee IE6 - since I don't have it available at the moment - but I can't see any reason why it wouldn't.

 

If you're using jQuery however, you can animate the movement and make it look a lot better:

 

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
window.onscroll = function() {
    setTimeout("scrollDiv()", 500);
}

function scrollDiv() {
    var top = (parseInt(document.body.scrollTop) + 10) + 'px';
    $('#scrolling_div').animate({top: top}, 500);
}
</script>

 

You'll probably want to play around with the delay and animation speed till you get a happy medium.

Link to comment
https://forums.phpfreaks.com/topic/222139-following-div/#findComment-1149467
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.