Reputation: 329
I just want to stick the div on top of the page
if someone scrolls the page then the green div stickdiv
should be automatically stick in the top
var left = document.getElementsByClassName("stickdiv");
for( var i = 0;i<left.length;i++){
var stop = (left[0].offsetTop);
window.onscroll = function (e) {
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
if (scrollTop >= stop) {
left.className += " stick"; //adding a class name
} else {
className = '';
}
}
}
why adding stick class on the div does not working - https://jsfiddle.net/kzk5qab2/1/
I just want to stick the div at top like yellow div on this - http://jsfiddle.net/qc4NR/
Upvotes: 1
Views: 118
Reputation: 1493
Depending on what browsers you need to support, you don't necessarily need JS for this.
.sticky {
position: sticky;
left: 0;
top: 0;
width: 100%;
}
Codepen: https://codepen.io/afisher88/pen/xJaxoP
Browser support for position sticky: https://caniuse.com/#search=position%3A%20sticky
Upvotes: 0
Reputation: 1090
You have looped into the array of left
items, but forget to reference the array index when trying to add the class name to the element.
var left = document.getElementsByClassName("stickdiv");
for (var i = 0; i < left.length; i++) {
var stop = (left[0].offsetTop);
window.onscroll = function(e) {
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
// left.offsetTop;
if (scrollTop >= stop) {
// get array item by index
left[0].classList.add('stick'); //adding a class name
} else {
// get array item by index
left[0].classList.remove('stick');
}
}
}
.stickdiv {
height: 50vh!important;
width: 100vh!important;
background-color: green!important;
}
.stick {
position: fixed;
top: 0;
margin: 0 0
}
#right {
float: right;
width: 100px;
height: 1000px;
background: red;
}
.des {
height: 300px;
width: 100%;
background-color: #000;
}
<div class="des"></div>
<div class="stickdiv"></div>
<div id="right"></div>
You don't even need to loop if you select the item directly, as in the following:
var left = document.querySelector(".stickdiv");
var stop = (left.offsetTop);
window.onscroll = function(e) {
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
// left.offsetTop;
if (scrollTop >= stop) {
left.classList.add('stick'); //adding a class name
} else {
left.classList.remove('stick');
}
}
Upvotes: 4