Reputation: 3009
I have a guessing game that uses a random number generator to assign a 'correct' box.
If the box that you guess is incorrect, I want it to fade out.
It does this, except I have to click it twice for it to fade.
On the first click, incorrect();
is successfully called, and then only on the second click is fade();
successfully called. i have 5 other functions with the same code as function one() that pertain to different boxes/divs and don't want to past the jquery 6 times.
Any ideas on how to fix this?
EDIT: here is a jsFiddle with more code to look at. Might make it easier to answer: http://jsfiddle.net/JMqxq/
function correct() {
document.getElementById("result").innerHTML = "You are correct!";
}
function incorrect() {
document.getElementById("result").innerHTML = "Sorry, you are incorrect.";
}
function fade() {
$(document).ready(function () {
$(temp2).click(function () {
$(this).animate({
"opacity": "0.25"
},
"slow");
});
});
}
function one() {
temp2 = "#one";
if (temp == 1) {
correct();
} else {
fade();
incorrect();
}
}
Upvotes: 0
Views: 191
Reputation: 13421
If you have jQuery included in your page, why don't you use it,
First, use data attribute to store some info about box,
<div class="box" id="one" data-id="1">
<div class="box" id="two" data-id="2">
<div class="box" id="three" data-id="3">
...
You can directly add click event listener for all div
elements which has a class as box
like this,
$("div.box").click(function() {
if (temp == $(this).data("id")) {
correct();
} else {
$(this).animate({"opacity": "0.25"}, "slow");
incorrect();
}
});
Upvotes: 2
Reputation: 8584
Replace your fade function with:
function fade(elem) {
$(elem).click(function () {
$(this).fadeOut();
});
}
function one() {
temp2 = "#one";
if (temp == 1) {
correct();
} else {
fade(temp2);
incorrect();
}
}
Upvotes: 1
Reputation: 3179
var temp2 = "#one";
function correct() {
document.getElementById("result").innerHTML = "You are correct!";
}
function incorrect() {
document.getElementById("result").innerHTML = "Sorry, you are incorrect.";
}
function one() {
if (temp == 1) {
correct();
}
else {
incorrect();
}
}
$(document).ready(function () {
$(temp2).click(function () {
$(this).animate({
"opacity": "0.25"
},
"slow");
});
});
First up you call jQuery's function when the document is ready, which means it is fully loaded.Second I have pulled out the temp2="#one" though that you easily be replaced as $("#one").click. For the code to work fully, I need information on where you have defined temp.
Upvotes: 2
Reputation: 1549
I would suggest trying to remove the $(document).ready wrapper. If your JavaScript is at the end of your body element, you won't need it. Either that or wrap your "one" method in the $(document).ready.
Upvotes: -1