5
\$\begingroup\$

Is there any way to reduce this?

//vars
defaultTextColor="#444"
correct = "#99CC00"
incorrect = "#FF4719"
answer1value = "1"  
answer2value = "3"  
totalquestions= "5" 

    //tap on the words
    $(function() {
        $("#word1a").click(function() {
            $("#word1b").css("text-decoration", "line-through").css("opacity", "0.2").css("color", defaultTextColor);
            $("#word1a").css("text-decoration", "none").css("opacity", "1").css("color", defaultTextColor);
            $("#slash1").css("text-decoration", "line-through").css("opacity", "0.1");
            saveanswers();
        });

        $("#word1b").click(function() {
            $("#word1b").css("text-decoration", "none").css("opacity", "1").css("color", defaultTextColor);
            $("#word1a").css("text-decoration", "line-through").css("opacity", "0.2").css("color", defaultTextColor);
            $("#slash1").css("text-decoration", "line-through").css("opacity", "0.1")
            saveanswers();
        });

        $("#word2a").click(function() {
            $("#word2b").css("text-decoration", "line-through").css("opacity", "0.2").css("color", defaultTextColor);
            $("#word2a").css("text-decoration", "none").css("opacity", "1").css("color", defaultTextColor);
            $("#slash2").css("text-decoration", "line-through").css("opacity", "0.1");
            saveanswers();
        });


        $("#word2b").click(function() {
            $("#word2b").css("text-decoration", "none").css("opacity", "1").css("color", defaultTextColor);
            $("#word2a").css("text-decoration", "line-through").css("opacity", "0.2").css("color", defaultTextColor);
            $("#slash2").css("text-decoration", "line-through").css("opacity", "0.1")
            saveanswers();
        });

        $("#word3a").click(function() {
            $("#word3b").css("text-decoration", "line-through").css("opacity", "0.2").css("color", defaultTextColor);
            $("#word3a").css("text-decoration", "none").css("opacity", "1").css("color", defaultTextColor);
            $("#slash3").css("text-decoration", "line-through").css("opacity", "0.1");
            saveanswers();
        });


        $("#word3b").click(function() {
            $("#word3b").css("text-decoration", "none").css("opacity", "1").css("color", defaultTextColor);
            $("#word3a").css("text-decoration", "line-through").css("opacity", "0.2").css("color", defaultTextColor);
            $("#slash3").css("text-decoration", "line-through").css("opacity", "0.1")
            saveanswers();
        });

    }); 


    //resets the inputs on change
    $(function() {
        $("#answer1").change(function() {
            {$(this).css("background-color", "lightgrey").css("color", defaultTextColor)}
        }); 
        $("#answer2").change(function() {
            {$(this).css("background-color", "lightgrey").css("color", defaultTextColor)}
        }); 
    }); 


    //Save storage
    function saveanswers() {
        input1save = $('#answer1 option:selected').val()
        localStorage['Physicsforyou-focustheeye-input1-6614-4506-8817-6439-3960'] = input1save      

        input2save = $('#answer2 option:selected').val()
        localStorage['Physicsforyou-focustheeye-input2-4475-3759-7632-7863-3079'] = input2save      

        word1asave = $('#word1a').css("text-decoration")
        localStorage['Physicsforyou-focustheeye-word1a-7790-2123-5352-3513-7817'] = word1asave  

        word1bsave = $('#word1b').css("text-decoration")
        localStorage['Physicsforyou-focustheeye-word1b-4620-2663-8547-2077-6191'] = word1bsave      

        word2asave = $('#word2a').css("text-decoration")
        localStorage['Physicsforyou-focustheeye-word2a-4176-8928-3185-6999-8057'] = word2asave  

        word2bsave = $('#word2b').css("text-decoration")
        localStorage['Physicsforyou-focustheeye-word2b-5094-8829-5741-5172-3780'] = word2bsave  

        word3asave = $('#word3a').css("text-decoration")
        localStorage['Physicsforyou-focustheeye-word3a-5294-2006-4289-2311-5537'] = word3asave  

        word3bsave = $('#word3b').css("text-decoration")
        localStorage['Physicsforyou-focustheeye-word3b-5429-1989-1854-1009-7066'] = word3bsave  

    }

    //Load storage
    $( document ).ready(function() {
        input1save = localStorage['Physicsforyou-focustheeye-input1-6614-4506-8817-6439-3960']
        input2save = localStorage['Physicsforyou-focustheeye-input2-4475-3759-7632-7863-3079']
        word1asave = localStorage['Physicsforyou-focustheeye-word1a-7790-2123-5352-3513-7817']
        word1bsave = localStorage['Physicsforyou-focustheeye-word1b-4620-2663-8547-2077-6191']
        word2asave = localStorage['Physicsforyou-focustheeye-word2a-4176-8928-3185-6999-8057']
        word2bsave = localStorage['Physicsforyou-focustheeye-word2b-5094-8829-5741-5172-3780']
        word3asave = localStorage['Physicsforyou-focustheeye-word3a-5294-2006-4289-2311-5537']
        word3bsave = localStorage['Physicsforyou-focustheeye-word3b-5429-1989-1854-1009-7066']
        tallyload = localStorage['Physicsforyou-focustheeye-tallyload-3405-1672-6158-8392-4746']

        $('#answer1').val(input1save)
        $('#answer2').val(input2save)
        $('#tally').html(tallyload)

        if (word1asave=="line-through")
            {$('#word1a, #slash1').css("text-decoration", "line-through").css("opacity", "0.2")
        }

        if (word1bsave=="line-through")
            {$('#word1b, #slash1').css("text-decoration", "line-through").css("opacity", "0.2")
        }

        if (word2asave=="line-through")
            {$('#word2a, #slash2').css("text-decoration", "line-through").css("opacity", "0.2")
        }

        if (word2bsave=="line-through")
            {$('#word2b, #slash2').css("text-decoration", "line-through").css("opacity", "0.2")
        }

        if (word3asave=="line-through")
            {$('#word3a, #slash3').css("text-decoration", "line-through").css("opacity", "0.2")
        }

        if (word3bsave=="line-through")
            {$('#word3b, #slash3').css("text-decoration", "line-through").css("opacity", "0.2")
        }

        });


    //Check Answers
    $(function() {
        $("#checkanswers").click(function() {
            input1 = $('#answer1 option:selected').val();
            input2 = $('#answer2 option:selected').val();
            score=0

            if (input1==answer1value)
            {
                $('#answer1').css("background-color", correct).css("color", "white");
                score++
            }
            else
            {
                $('#answer1').css("background-color", incorrect).css("color", "white");
            }


            if (input2==answer2value)
            {
                $('#answer2').css("background-color", correct).css("color", "white");
                score++
            }
            else
            {
                $('#answer2').css("background-color", incorrect).css("color", "white");
            }


            if ($('#word1a').css("text-decoration") == 'line-through')
            {
                $('#word1b').css("color", correct);
                score++
            }

            if ($('#word1b').css("text-decoration") == 'line-through')
            {
                $('#word1a').css("color", incorrect);
            }

            if ($('#word2a').css("text-decoration") == 'line-through')
            {
                $('#word2b').css("color", correct);
                score++
            }

            if ($('#word2b').css("text-decoration") == 'line-through')
            {
                $('#word2a').css("color", incorrect);
            }

            if ($('#word3a').css("text-decoration") == 'line-through')
            {
                $('#word3b').css("color", correct);
                score++
            }

            if ($('#word3b').css("text-decoration") == 'line-through')
            {
                $('#word3a').css("color", incorrect);
            }


            finalscore= Math.round(score/totalquestions*100)
            $('#tally').html("You scored " + score + "/" + totalquestions + " - " + finalscore + "%");

            tallysave = "You scored " + score + "/" + totalquestions + " - " + finalscore + "%"
            localStorage['Physicsforyou-focustheeye-tallyload-3405-1672-6158-8392-4746'] = tallysave

            tallylog = finalscore
            localStorage['Physicsforyou-focustheeye-tallylog-7600-5956-8912-6767-3256'] = tallylog              
        }); 
    }); 

    //clear answers
    $(function() {
        $("#clearanswers").click(function() {
            $('#answer1').val("0")
            $('#answer2').val("0")
            $('#answer1, #answer2').css("background-color", "lightgrey").css("color", "black");
            $("#word1a, #word1b, #slash1, #word2a, #word2b, #slash2, #word3a, #word3b, #slash3").css("text-decoration", "none").css("opacity", "1").css("color", defaultTextColor)
            saveanswers();
        });
    }); 

    //Thumbs Load
    $(document).ready(function () {
        if (localStorage.getItem('Physicsforyou-focustheeye-thumbs-3747-4345-2469-7020-2251') === 'up') {
        thumbsup();
        }
        else if (localStorage.getItem('Physicsforyou-focustheeye-thumbs-3747-4345-2469-7020-2251') === 'down') {
        thumbsdown();
        }
    });

    //Thumbs Save
    function thumbsup() {
        $("#thumbsdown").removeClass("btn-danger").addClass("btn-default");
        $("#thumbsup").removeClass("btn-default").addClass("btn-success");
        localStorage.setItem('Physicsforyou-focustheeye-thumbs-3747-4345-2469-7020-2251', 'up');
     }

    function thumbsdown() {
        $("#thumbsdown").removeClass("btn-default").addClass("btn-danger");
        $("#thumbsup").removeClass("btn-success").addClass("btn-default");
        localStorage.setItem('Physicsforyou-focustheeye-thumbs-3747-4345-2469-7020-2251', 'down');
     }
\$\endgroup\$

3 Answers 3

6
\$\begingroup\$
  • You should be using CSS with style sheets, not by setting all styles on the elements directly. You can switch the styles for a certain element by applying and unapplying a specific class.

  • Your naming scheme suggests that you want more complex data structures, e.g. an array of inputs, or an array of word objects like {slash: ..., a: ..., b: ...} instead of slash2, word2a, word2b. You can then cache the selectors in those fields.

    For example, this piece of code

    //resets the inputs on change
    $(function() {
        $("#answer1").change(function() {
            {$(this).css("background-color", "lightgrey").css("color", defaultTextColor)}
        }); 
        $("#answer2").change(function() {
            {$(this).css("background-color", "lightgrey").css("color", defaultTextColor)}
        }); 
    });
    

    Could become something like

    $(function() {
      for(var i = 0; i < answers.length; i++) {
        answers[i].change(function() {
          $(this).css(...);
        });
      }
    });
    

    where answers is an array of jQuery objects.

  • The same ideas hold true for your save data. Do not use variable names to impose a hierarchy, but instead complex data structures. Repetitive code like

    if (word1asave=="line-through")
        {$('#word1a, #slash1').css("text-decoration", "line-through").css("opacity", "0.2")
    }
    ...
    

    could become

    var words = savedata.words;   // [{a:String, b:String, $:{a:$, b:$, slash:$}}, ...]
    for (var i = 0; i < words.length; i++) {
      var word = words[i];
      if (word.a === "line-through") {
         word.$.a    .css(...);
         word.$.slash.css(...);
      }
      if (word.b === "line-through") {
         word.$.b    .css(...);
         word.$.slash.css(...);
      }
    }
    

    I am sure you now see that this can be abstracted further.

  • Every time you use == instead of ===, a kitten dies. Granted, it isn't necessary in your code, but it's still good style.

  • I see you are leaving out many semicolons. I'd suggest to not rely on automatic semicolon insertion, and finish each line with an operator.

\$\endgroup\$
3
\$\begingroup\$

I didn't see the entire code, but at first glance, there is some redundancy in there.

For example, this piece of code:

$(function() {
    $("#word1a").click(function() {
        $("#word1b").css("text-decoration", "line-through").css("opacity", "0.2").css("color", defaultTextColor);
        $("#word1a").css("text-decoration", "none").css("opacity", "1").css("color", defaultTextColor);
        $("#slash1").css("text-decoration", "line-through").css("opacity", "0.1");
        saveanswers();
    });

    $("#word1b").click(function() {
        $("#word1b").css("text-decoration", "none").css("opacity", "1").css("color", defaultTextColor);
        $("#word1a").css("text-decoration", "line-through").css("opacity", "0.2").css("color", defaultTextColor);
        $("#slash1").css("text-decoration", "line-through").css("opacity", "0.1")
        saveanswers();
    });

    $("#word2a").click(function() {
        $("#word2b").css("text-decoration", "line-through").css("opacity", "0.2").css("color", defaultTextColor);
        $("#word2a").css("text-decoration", "none").css("opacity", "1").css("color", defaultTextColor);
        $("#slash2").css("text-decoration", "line-through").css("opacity", "0.1");
        saveanswers();
    });


    $("#word2b").click(function() {
        $("#word2b").css("text-decoration", "none").css("opacity", "1").css("color", defaultTextColor);
        $("#word2a").css("text-decoration", "line-through").css("opacity", "0.2").css("color", defaultTextColor);
        $("#slash2").css("text-decoration", "line-through").css("opacity", "0.1")
        saveanswers();
    });

    $("#word3a").click(function() {
        $("#word3b").css("text-decoration", "line-through").css("opacity", "0.2").css("color", defaultTextColor);
        $("#word3a").css("text-decoration", "none").css("opacity", "1").css("color", defaultTextColor);
        $("#slash3").css("text-decoration", "line-through").css("opacity", "0.1");
        saveanswers();
    });


    $("#word3b").click(function() {
        $("#word3b").css("text-decoration", "none").css("opacity", "1").css("color", defaultTextColor);
        $("#word3a").css("text-decoration", "line-through").css("opacity", "0.2").css("color", defaultTextColor);
        $("#slash3").css("text-decoration", "line-through").css("opacity", "0.1")
        saveanswers();
    });

}); 

Can be shortened to this:

$(".word").click(function () {
    var clickedID = $(this).attr("id");
    var other = 'b';
    if(clickedID[1] != 'a'){
        other = 'a';
    }
    $(this).css("text-decoration", "none").css("opacity", "1").css("color", defaultTextColor);
    $("#" + clickedID[0] + other).css("text-decoration", "line-through").css("opacity", "0.2").css("color", defaultTextColor);
    $("#slash" + clickedID[0]).css("text-decoration", "line-through").css("opacity", "0.1");
    saveanswers();
});

Here's a fiddle that demonstrates what I mean

Hope this helped. Feel free to ask if you have any questions. :)

\$\endgroup\$
1
\$\begingroup\$

You are using neither jQuery nor CSS effectively. Basically, you don't want to address each item in the DOM individually as a special case. Instead, you should take advantage of jQuery's ability to operate on many items at once based on a selector. See this jsFiddle for a more compact solution.

Your JavaScript code has no business setting styles; that's the stylesheet's job. At most, your code should add or remove classes from elements. For example, the stylesheet should look like:

div.wordpair button.word.struck {
    text-decoration: line-through;
    color: #444;
    opacity: 0.2;
}
div.wordpair button.word.selected {
    text-decoration: none;
    color: #444;
    opacity: 1;
}
div.wordpair button.word.correct {
    background-color: #99cc00;
    color: white;
}
div.wordpair button.word.incorrect {
    background-color: #ff4719;
    color: white;
}

Then somewhere in your JavaScript, you would have a function like:

function selectWord(word) {
    $(word).siblings()
               .removeClass('selected')
               .addClass('struck')
               .andSelf()
                   .removeClass('correct')
                   .removeClass('incorrect')
               .end()
           .end()
           .removeClass('struck')
           .addClass('selected');
}
$('div.wordpair button.word').click(function() {
    selectWord(this);
    saveAnswers();
});

That's all the code you need to implement the basic user interaction! The rest of the job is to figure out how to implement loading, saving, and checking similarly smartly. Here's the rest of the code to do that:

var ANSWERS = {
    '#wordpair1': '#word1a',
    '#wordpair2': '#word2b',
    '#wordpair3': '#word3a',
};
var STORAGE_PREFIX = 'Physicsforyou-focustheeye-';

function clear() {
    $('div.wordpair button.word').removeClass('selected')
                                 .removeClass('struck')
                                 .removeClass('correct')
                                 .removeClass('incorrect');
}

function saveAnswers() {
    var selectedWords = getSelectedWords()
    for (var key in selectedWords) {
        localStorage[STORAGE_PREFIX + key] = selectedWords[key];
    }
}

function loadAnswers() {
    for (var key in localStorage) {
        if (0 == key.indexOf(STORAGE_PREFIX + '#wordpair')) {
            selectWord(localStorage[key]);
        }
    }
}

function getSelectedWords() {
    var selectedWords = {};
    $('div.wordpair').each(function() {
        var sel = $(this).children('button.word.selected').attr('id');
        selectedWords['#' + $(this).attr('id')] = sel ? '#' + sel : null;
    });
    return selectedWords;
}

function checkAnswers() {
    var selectedWords = getSelectedWords();
    for (var key in ANSWERS) {
        var sel = selectedWords[key];
        if (sel) {
            $(sel).addClass(ANSWERS[key] == sel ? 'correct' : 'incorrect');
        } else {
            // Unanswered question
            $(key).children('button.word')
                  .addClass('incorrect');
        }
    }
}

$('#checkanswers').click(function() {
    checkAnswers();
});
$('#clearanswers').click(function() {
    clear();
    saveAnswers();
});
$(document).ready(function() {
    loadAnswers();
});
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.