Reputation: 11
I have written a code which shows question on click and also shows answer for certain period of time. The code works fine when there is no fadeOut function inside the code. As soon as I put the fadeOut function, the question and answer is shown only once. After that only question is shown . Why is this happening ?
Here is my code link :http://jsfiddle.net/sagesony/6qDap/1058/
and the code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<body>
<p>Question: <span id="question"></span></p>
<p>Answer: <span id="answer"></span></p>
<input id="start" type="button" value="start"/>
<input id="show" type="button" value="show answer"/>
<script>
document.getElementById("start").onclick=function(){
var i=Math.round(Math.random()*3);
var verbs=["play","run","go","kill"];
document.getElementById("question").innerHTML=verbs[i];
document.getElementById("show").onclick=function(){
var answers=["golf","dog","school","none"];
document.getElementById("answer").innerHTML=answers[i];
$("#answer").fadeOut(1000);
};
};
</script>
Upvotes: 0
Views: 52
Reputation: 73896
This happens since after calling the fadeOut()
method the answer
span is hidden forever. You will have to do something to show it again like below:
var i = 0;
var verbs = ["play", "run", "go", "kill"];
var answers = ["golf", "dog", "school", "none"];
$('#start').click(function () {
i = Math.round(Math.random() * 3);
$('#question').html(verbs[i]);
});
$('#show').click(function () {
$("#answer").html(answers[i]).show().fadeOut(1000);
});
Upvotes: 0
Reputation: 1307
You should show it again: http://jsfiddle.net/6qDap/1063/
$("#answer").fadeOut(1000, function(){
$(this).show().text('');
});
Upvotes: 0
Reputation: 1926
because fadeOut is setting your element to display:none; after fading. so, you have to set this element visible again to fadeOut again.
just use:
.show()
to do this.
http://jsfiddle.net/Valtos/6qDap/1060/
Upvotes: 2
Reputation: 388316
You need to use a delay like
var verbs = ["play", "run", "go", "kill"];
var answers = ["golf", "dog", "school", "none"];
//register click handler
$('#start').click(function () {
var i = Math.round(Math.random() * 3);
$("#question").html(verbs[i]);
$('#show').click(function () {
$("#answer").html(answers[i]).delay(1000).fadeOut();
})
})
Upvotes: 0