user3615820
user3615820

Reputation: 43

Div not getting fixed on scrolling

I am trying to make a div fixed to top when I scroll down. But somehow the code is not working...

Please check the code below:

<div id="column-left" class="column_absolute">
      My name is Peter
</div>

<script type="text/javascript">

function window_onload() {
    alert("hi");
    window.addEventListener("scroll", navbar_reset_top, false); 
}

var navbar_top = 100;
function navbar_reset_top() {

    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    if (scrollTop > navbar_top && column-left.className === "column_absolute") {
        document.getElementById("column-left").className="column_fixed";
    }
    else if (scrollTop < navbar_top && column-left.className === "column_fixed") {
        document.getElementById("column-left").className="column_absolute";
    }
}

</script>

<style type="text/css">
.column_absolute {
    width: 220px;
    padding: 0px 15px 0 0px;
    border-right: 1px solid #eee;
    margin-left:20px;
    position:absolute;
}
.column_fixed {
    width: 220px;
    position:fixed;
    margin-top:0px;
    padding: 0px 15px 0 0px;
    border-right: 1px solid #eee;
}
</style>
</head>
<body onload="javascript:window_onload()">

When I'm scrolling down, the div mentioned above should be fixed.

Please check the code and correct me please...

Upvotes: 0

Views: 65

Answers (2)

K K
K K

Reputation: 18099

Everything works fine in your code, except that you have undefined variable column-left. Probably you missed defining it.

Demo: http://jsfiddle.net/GCu2D/137/

function window_onload() {
    alert("hi");
    document.addEventListener("scroll", navbar_reset_top, false);
}
var navbar_top = 100;

function navbar_reset_top() {
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    var column_left = document.getElementById("column-left");
    if (scrollTop > navbar_top && column_left.className === "column_absolute") {
        document.getElementById("column-left").className = "column_fixed";
    } else if (scrollTop < navbar_top && column_left.className === "column_fixed") {
        document.getElementById("column-left").className = "column_absolute";
    }
}

I used column_left instead of column-left

Upvotes: 1

Gal Ziv
Gal Ziv

Reputation: 7372

the id of the div is column_fixed. you should use # insead of . in your css class to use id selector.

 #column_fixed
 {

 width: 220px;
 position:fixed;
 margin-top:0px;
 padding: 0px 15px 0 0px;
 border-right: 1px solid #eee;

}

Upvotes: 0

Related Questions