In my JavaScript quiz, I have two functions below which are not DRY. What i want to do is to cut it, so everything below var = text
would be used only once not twice.
My concept is to enclose these two functions in bigger function (e.g. guess()
) and keep the trimmed correctGuess()
and incorrectGuess()
within it.
Now here's the question: how can I call such nested function as described above from outside scope. I was thinking about something like: guess().correctGuess()
which is obviously wrong but I wanted to share a concept.
Additionally, when e.g. correctGuess()
would be called, is rest of the commands within our main guess()
function would be executed?
function correctGuess(i) {
totalScore++;
questionNumber++;
var text = "Correct!";
var updatePage = ['<div id="answerDiv">' +
'<h1>' + text + '<h1>' +
'<h2>Total Score: ' + totalScore + '</h2></div>'
];
mainContent[html](updatePage);
$('#answerDiv')[fadeIn]("slow");
$('#answerDiv').append('<button id="nextButton">Next Question</button>');
$('#nextButton').on('click', function() {
if (questionNumber == allQuestions.length && totalScore <= 4) {
results()
} else {
question(questionNumber)
}
})
};
function incorrectGuess(i) {
totalScore--;
questionNumber++;
var text = "Wrong!";
var updatePage = ['<div id="answerDiv">' +
'<h1>' + text + '<h1>' +
'<h2>Total Score: ' + totalScore + '</h2></div>'
];
mainContent[html](updatePage);
$('#answerDiv')[fadeIn]("slow");
$('#answerDiv').append('<button id="nextButton">Next Question</button>');
$('#nextButton').on('click', function() {
if (questionNumber == allQuestions.length && totalScore <= 4) {
results();
} else {
question(questionNumber);
}
});
};