When “button” is clicked in my script it brings back an image file (“#mypic”), a sound file (“#mysoundclip”) and a class that styles a word to spell (“#picknext”).
The thing is, I want the button to repeat its action 3 times before moving on to the next image, sound and style. How would I do this?
$('#pickNext').click(function() {
// remove the class from all td's
$('td').removeClass('spellword');
// pick a random word
var r = rndWord;
while (r == rndWord) {
rndWord = Math.floor(Math.random() * (listOfWords.length));
}
// apply class to all cells containing a letter from that word
$('td[data-word="' + listOfWords[rndWord].name + '"]').addClass('spellword');
});
var audio = $("#mysoundclip")[0];
var i = 0;
$(".minibutton").click(function() {
var noExist = $('td[data-word=' + listOfWords[rndWord].name + ']').hasClass('wordglow2');
if (noExist && i >= 3) {
$('#pickNext').click();
i = 0;
} else {
$("#mysoundclip").attr('src', listOfWords[rndWord].audio);
audio.play();
pic = $("#mypic").attr('src', listOfWords[rndWord].pic);
pic.show();
$i++;
}
});
Keep track of how many times the button has been pressed using jQuery’s .data() function. You’d set a counter and then increment, doing things when it hits 3. A basic outline:
If I understand your code, it would look something like this:
This will allow you to add more buttons if you want to, and in any event is good coding practice. It may be wise to also add a ‘maxClicks’ data attribute that is set to ‘3’ that gets checked, so that you can vary how many clicks it needs.
Looking at the code you put up your jsFiddle, there are several things that need to be fixed. Notably, you seem to be confusing the “type” attribute of your inputs with the id. Each id should only be used once, you’re using pickNext twice. That will break all kinds of things. You also are using a type of “button2”, which isn’t valid. Your $(‘button’) and $(‘button2’) click events won’t work as you anticipated, because those are looking for elements with the tag of and . So the first event will be fired any time any button is pressed, and the second never will. The $(‘#pickNext’) click event, since you’re using pickNext twice, will probably only fire for the second button. You should probably give them id’s of “pickNext” and “reset”, and then refer to those selectors for your click events.
Long story short: get the rest of your code working, and then worry about getting things to happen three times.