Reputation:
Imagine you're using an image to call a function like this:
<img src="images/next.png" alt="" class="transition opacity" onclick="nextQ()" />
and you have a function with this:
function nextQ(id) {
var prevQuestion = 0;
var currentQuestion = 1;
prevQuestion++;
currentQuestion++;
var elem = document.getElementById("q" + prevQuestion);
elem.parentNode.removeChild(elem);
document.getElementById("q" + currentQuestion).style.cssText = 'display:inline;';
next.style.cssText = 'display:none;';}
How could I make it so every time you click on the image the function happens. At the moment it only happens when you click on it the first time, and nothing happens when you click the second time.
Upvotes: 1
Views: 5209
Reputation: 10074
onclick="nextQ()"
Just an FYI, using event handlers in the mark up is bad practise. See this SO topic.
Formatting and indentation aside the problem is the variable your using to save state are being lost and recreated each time the function executes. You need to move them to a higher scope and manage them there:
var nextQ = (function() {
var prevQuestion = 0;
var currentQuestion = 1;
function nextQ() { // You never referenced the id argument.
prevQuestion++;
currentQuestion++;
var elem = document.getElementById("q" + prevQuestion);
elem.parentNode.removeChild(elem);
document.getElementById("q" + currentQuestion).style.cssText = 'display:inline;';
next.style.cssText = 'display:none;'; // This is not defined!
}
return nextQ;
})();
Lastly the above code doesn't offer must in the way of manipulation or inspection. Although functional and the correct (simplest-ish) answer I'm going to go further and really abstract things:
function QuestionStateMachine(id_prefix) {
this.id_prefix = id_prefix;
this.currentQuestion = 1;
}
QuestionStateMachine.prototype.nextQ = function() {
var current = this.currentQuestion++;
var previous = current - 1;
var next = current + 1;
var prevEl = document.getElementById('' + this.id_prefix + previous);
var currentEl = document.getElementById('' + this.id_prefix + current)
var nextEl = document.getElementById('' + this.id_prefix + next)
prevEl.parentNode.removeChild(prevEl);
currentEl.style.cssText = 'display:inline;';
nextEl.style.cssText = 'display:none;';
};
var quizSM = new QuestionStateMachine('q');
document.getElementsByClassName('quiz-button').forEach(function(button) {
button.addEventListener('click', quizSM.nextQ.bind(quizSM));
});
Upvotes: 1
Reputation: 1977
your prevQuestion && your currentQuestion are resetting each time you run that function, if you want them to increment each time make them global variables ( place them outside your function ), like this:
var prevQuestion = 0;
var currentQuestion = 1;
function nextQ(id) {
prevQuestion++;
currentQuestion++;
}
here's a working example http://jsfiddle.net/Tt8f6/
Upvotes: 1