Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Div Position to Fixed When Scrolled to Position - jQuery

I am working with a right sidebar that contains three sliders aligned vertically. I would like to have the sidebar's position to be fixed when I scroll down to 200 pixels. Here's my code so far:

$(document).ready(function() {
    window.onscroll = function() {
        if (window.pageYOffset >= 200){
            $('.col-right').css({position: 'fixed', right: '490px'});
        }
    }
}

Nothing happens when I use this code. It detects that I am scrolling but it doesn't set the CSS properties to the "col-right" class, which is the sidebar. Am I doing this right?

like image 915
Daniel Harris Avatar asked Feb 16 '23 20:02

Daniel Harris


2 Answers

OK, I figured it out. I changed $ to jQuery and everything works. Here is my working solution:

jQuery(document).ready(function(){
    window.onscroll = function() {
        if (window.pageYOffset >= 200){
            jQuery('.col-right').css({position: 'fixed', right: '490px', top: '40px'});
        }
        else {
            jQuery('.col-right').css({position: '', right: '', top: ''});
        }
    }
});
like image 61
Daniel Harris Avatar answered Feb 19 '23 12:02

Daniel Harris


replace:

.css({position: fixed, right: 490px});

with

.css({position: 'fixed', right: '490px'});

strings should be quoted!

like image 44
adeneo Avatar answered Feb 19 '23 11:02

adeneo