dafie
dafie

Reputation: 1169

Stick div on screen when user is scrolling

I want to make my div right to stick on screen when user is scrolling. This is example situation: https://jsfiddle.net/gwjehuzf/

I tried a lot, but without success. Something like this:

$(window).scroll(function () {

    if ($(document).scrollTop() > 400) {
        console.log("a");
        var newPos = $(document).scrollTop() + 400;
        $('.right').css({ top: newPos });
    }

    else {
        $('.right').css({ top: 400 });
    }
})

for some reason is not working. Any ideas?

Upvotes: 2

Views: 201

Answers (5)

AzarJad
AzarJad

Reputation: 1563

just use css .right{position:sticky; top:0; overflow:hidden;}

Upvotes: 4

Eddie
Eddie

Reputation: 390

You can achieve this by adding position: sticky to .right and setting top: 0.

.right {
  position: fixed;
  top: 0;
}

Your JSFiddle corrected here.

Upvotes: 0

Hassan Siddiqui
Hassan Siddiqui

Reputation: 2845

Just need to add few CSS, we'll resolve your issue. Thanks

.right {
  position: fixed;
  right: 0;
  width: calc(100% - 200px);
}

Upvotes: 2

Abhishek
Abhishek

Reputation: 1006

Add this css in your code

.right {
   position: sticky; 
   top: 5px; 
}

Upvotes: 1

NullDev
NullDev

Reputation: 7321

No JavaScript needed for that. Use position: fixed for the .right div.
If it disappears, give it a width (maybe about 80%) and right: 0:

.right {
    position: fixed;
    width: 80%;
    right: 0;
}

Upvotes: 0

Related Questions