I have a chain of if statements that control the opacity of an image depending on the .scrollTop() of the page. Here are the rather unsightly chain of if statements:
if (wScroll > 180) {
$(".coffee").css("opacity", 1);
}
else if (wScroll <= 180 && wScroll > 162) {
$(".coffee").css("opacity", 0.9);
}
else if (wScroll <= 162 && wScroll > 144) {
$(".coffee").css("opacity", 0.8);
}
else if (wScroll <= 144 && wScroll > 126) {
$(".coffee").css("opacity", 0.7);
}
else if (wScroll <= 126 && wScroll > 108) {
$(".coffee").css("opacity", 0.6);
}
else if (wScroll <= 108 && wScroll > 90) {
$(".coffee").css("opacity", 0.5);
}
else if (wScroll <= 90 && wScroll > 72) {
$(".coffee").css("opacity", 0.4);
}
else if (wScroll <= 72 && wScroll > 54) {
$(".coffee").css("opacity", 0.3);
}
else if (wScroll <= 54 && wScroll > 36) {
$(".coffee").css("opacity", 0.2);
}
else if (wScroll <= 36 && wScroll > 18) {
$(".coffee").css("opacity", 0.1);
}
else if (wScroll <= 18) {
$(".coffee").css("opacity", 0);
}
I would like to condense these down into a for loop. My attempt at it only works when scrolling down (adding opacity) but not when scrolling up (subtracting opacity). Sometimes it doesn't work at all. This is what I have come up with:
var lessThanEqualTo = 18;
var greaterThan = 0;
var inc = 18;
var opacityVal = 0;
$(window).scroll(function() {
var wScroll = Math.round($(this).scrollTop());
var count = 0;
if (wScroll > 1) {
for (var i = 0; i < 10; i++) {
var opacity = $(".coffee").css("opacity", (opacityVal/10));
if (wScroll <= lessThanEqualTo && wScroll > greaterThan) {
opacity;
opacityVal++;
lessThanEqualTo += inc;
greaterThan += inc;
}
}
}
$(".coffee").css({
"transform" : "translate(0px," + wScroll/1.5 + "%)"
});
});
Any help or advice on this would really be helpful.
Aucun commentaire:
Enregistrer un commentaire