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...
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
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.