Reputation: 1
First, I know this has been covered multiple times, but I just can't figure out how to insert the script properly...
I want a div to change opacity when scroll is getting down...
what I'm having now: FIDDLE
$(window).scroll(function() {
var st = $(this).scrollTop();
$('#liners').each(function(index) {
if (($(this).offset().top-st) < 50) {
$(this).css({
'opacity': (0 + (st / $(this).offset().top))
});
} else {
$(this).css({'opacity': 0.1});
}
})
});
It doesn't work AT ALL, not even near to.. I would need help I don't know if i'm writing it correctly too!
Thanks for answers and if you need more infos from me just ask!
Upvotes: 0
Views: 1097
Reputation: 3765
Next time, please test your fiddle (you've put JS+CSS in the wrong boxes and you didn't include jQuery).
I've change CSS definition to make it easier to test (I used smaller height than you). Other than that, here is the relevant JS code:
$('div#liners').scroll(function() {
var st = $(this).scrollTop();
var h = this.scrollHeight;
$(this).css({
'opacity': 1 - st / h
});
});
You need to capture div
's scroll, get the size of the content (h
in my code) and to scroll position.
Edit: It just occurred to me you want it all to depend on the window scroll, not div content (I don't see a purpose for that, so I didn't think of it before). In that case, just adapt my code to capture window's scroll, as you did in your original attempt.
Upvotes: 1