M Usman Shafique
M Usman Shafique

Reputation: 361

Always visible div while scrolling

On my aspx page, I have two left and right portions. I want to show always left side (which is actually a 'div' containig treeview) while scrolling the right side (which are actual contents of page). Thanks

Upvotes: 27

Views: 62067

Answers (5)

Grilse
Grilse

Reputation: 3917

Fast forward to 2020, and it is now possible to do this with CSS.

<div style="position: sticky; top: 0;"> Tree view </div>

The user npas explains this quite nicely:

top is the distance to the viewport top the div should stay at when you scroll. Specifying top is mandatory. (…)

The sticky div will act like a normal div in all ways except when you scroll past it, then it will stick to the top of the browser.

Here's a jsfiddle to give you an idea.

MDN documentation

Supported by all modern browsers

Upvotes: 19

user3609824
user3609824

Reputation: 33

The problem is that when the block moves, it gets attention and ability to concentrate on reading.

To remedy this using this function.

This code is perfect :

(change "220" and "46px" if necessary)

  var $scrollingDiv = $("#scrollingDiv");

$(window).scroll(function(){     
if ($(window).scrollTop()>220)       {
            $scrollingDiv
                .css("position",'fixed' )  
                .css("top",'46px' )           
        } else {
 $scrollingDiv
                .css("position",'' )    
                .css("top",'' )             
        }
        });

Upvotes: 3

Despertaweb
Despertaweb

Reputation: 1820

Hi I found the best solution! As always JQUERY saving my life !!

Just put a Div called as you wan, I've chosen the same in the example below: #scrollingDiv.

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script>
    $().ready(function() {
        var $scrollingDiv = $("#scrollingDiv");

        $(window).scroll(function(){            
            $scrollingDiv
                .stop()
                .animate({"marginTop": ($(window).scrollTop() )}, "slow" );         
        });
    });
</script>

I took that code from a website, it works and it's pretty easy to understand.

Upvotes: 21

Daniel Casserly
Daniel Casserly

Reputation: 3500

You need to set the position of the div to Fixed in CSS. See this link for more information. You will need to set position using the top and left in css as well so it knows where to fix it!

Upvotes: 4

danbee
danbee

Reputation: 506

You need to put position: fixed; on the div element. That will anchor it to the viewport.

Upvotes: 23

Related Questions