HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Increasing opacity based on an element's location

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
opacityelementincreasingbasedlocation

Problem

I've got a piece of code that takes an element, checks where it is, and if it's beyond a set place in the viewport, make the opacity increase to 1. I've made the code so that it only runs the checks if they're needed, the problem is that the code looks atrocious, and I suspect there's a better way for me to be doing it.

```
var $wheresThisAt = viewportHeight*4;
if (scrolled > ($wheresThisAt))
{
//there has to bve a better way...
$('.salafoot').css('opacity', '0');
$('#salamander-1').css('opacity', '1');
if (scrolled > (($wheresThisAt)+20)){
$('#salamander-2').css('opacity', '1');
if (scrolled > (($wheresThisAt)+40)){
$('#salamander-3').css('opacity', '1');
if (scrolled > (($wheresThisAt)+60)){
$('#salamander-4').css('opacity', '1');
if (scrolled > (($wheresThisAt)+80)){
$('#salamander-5').css('opacity', '1');
if (scrolled > (($wheresThisAt)+100)){
$('#salamander-6').css('opacity', '1');
if (scrolled > (($wheresThisAt)+120)){
$('#salamander-7').css('opacity', '1');
if (scrolled > (($wheresThisAt)+140)){
$('#salamander-8').css('opacity', '1');
if (scrolled > (($wheresThisAt)+160)){
$('#salamander-9').css('opacity', '1');
if (scrolled > (($wheresThisAt)+180)){
$('#salamander-10').css('opacity', '1');
if (scrolled > (($wheresThisAt)+200)){
$('#salamander-11').css('opacity', '1');
if (scrolled > (($wheresThisAt)+220)){
$('#salamander-12').css('opacity', '1');
if (scrolled > (($wheresThisAt)+240)){
$('#salamander-13').css('opacity', '1');
if (scrolled > (($wheresThisAt)+260)){
$('#salamander-14').css('opacity', '1');
if (scrolled > (($wheresThisAt)+2

Solution

Gah! Thanks for coming here.

Essentially, all your if-statements have the following structure:

if (scrolled > (($wheresThisAt)+(N * 20))){
    $('#salamander-(N + 1)').css('opacity', '1');


So we can comfortably roll that into a loop:

for (var i = 0; i < 35; i++) {
    if (scrolled <= ($wheresThisAt + i * 20)) {
        break;
    }
    $("#salamander-" + (i + 1)).css('opacity', '1');
}

Code Snippets

if (scrolled > (($wheresThisAt)+(N * 20))){
    $('#salamander-(N + 1)').css('opacity', '1');
for (var i = 0; i < 35; i++) {
    if (scrolled <= ($wheresThisAt + i * 20)) {
        break;
    }
    $("#salamander-" + (i + 1)).css('opacity', '1');
}

Context

StackExchange Code Review Q#45596, answer score: 17

Revisions (0)

No revisions yet.