Jump to content

Following Div.


IwnfuM

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.