user1289939
user1289939

Reputation:

Stick a div to a div when scroll

Please check fiddle: http://jsfiddle.net/howtoplease/f8sXN/4/

I want to make .float sticky by jQuery to .right when scroll.

HTML code

<div class="main">
    <div class="float">
        float
    </div>
    <div class="right">
        Stick float to me
    </div>
</div>

CSS code

.main{
    margin-bottom:30px;

}
.float{
    background:  #333333;
    color: #FFFFFF;
    float: left;
    height: 40px;
    margin-right: 20px;
    width: 40px;
}
.right{
    background: none repeat scroll 0 0 #AAAAAA;
    height: 245px;
    overflow: hidden;    
}

Upvotes: 2

Views: 136

Answers (2)

Mark S
Mark S

Reputation: 3799

This should do:

$(window).scroll(function(){
var st = $(this).scrollTop();

$('.main').each(function(){
    var $this = $(this), 
        offset = $this.offset(),
        h = $this.height(),
        $float = $this.find('.float'),
        floatH = $float.height();

    if(st >= offset.top && st < offset.top + h - floatH){
        $float.css({'position':'fixed'});
    }else{
        $float.css({'position':'absolute'});
    }
})
});

CSS:

.main{
    margin-bottom:30px;
    /* set main to realtive so float won't move out bounds */
    position:relative;
}

.float{
    background:  #333333;
    color: #FFFFFF;
    height: 40px;
    width: 40px;
    /* set top to 0 and position to absolute*/
    top:0;
    position:absolute;
}

.right{
    background: none repeat scroll 0 0 #AAAAAA;
    height: 245px;
    overflow: hidden; 
    /* the float width:40 plus its margin-right:20 that I removed*/
    margin-left:60px; 
}

I've updated the answer to solve the issue on '.right' — maintaining the same width and position.

Similar to @UDB solution, but on that method (changing 'margin-top') I noticed the '.float' sometimes shaking especially on long scroll and scrolling fast this happens: enter image description here

On my new solution we're only changing the position property so no issue so far.

See this jsfiddle.

Thanks also to @Zeaklous and @UDB ideas.

Upvotes: 2

Udit Bhardwaj
Udit Bhardwaj

Reputation: 1781

altered Mark S's answer to keep the .float on left side like the page whose link is provided in comment

$(window).scroll(function () {
var st = $(this).scrollTop();

$('.main').each(function () {
    var $this = $(this),
        offset = $this.offset(),
        h = $this.height();

    if (st >= offset.top && st < offset.top + h - 40) {
        $this.find('.float').css({
            'margin-top': st - offset.top + 'px'
        });
    } else if (st >= offset.top + h + 30/*.main margin-bottom*/) {
        $this.find('.float').css({
            'margin-top': 'auto'
        });
    }


})
});

DEMO

Upvotes: 0

Related Questions