I am stuck why this code is not working. Why Image position not fixed when i scroll down the window.
I know this is a very common question help would be appreciated.
$(window).scroll(function () { if($(window).scrollTop() === 200){ $("#dataImg").css({'position':'fixed','top':'0px'}); } });
.container { height: 1500px; background: #000; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <img src="http://www.placehold.it/200x300" id="dataImg"> </div>
I think the problem is with the "$(window).scrollTop === 200". You want to use > or < depending on your situation like this:
$(window).scroll(function () {
if($(window).scrollTop() > 200){
$("#dataImg").css({'position':'fixed','top':'0px'});
}
});
I suppose you want to fix that image when you scroll down over 200px. You can change your Javascript code to following:
$(window).scroll(function () {
if($(window).scrollTop() >= 200){
$("#dataImg").css({'position':'fixed','top':'0px'});
} else {
$("#dataImg").css({'position': '', 'top' : ''});
}
});
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.