Reputation: 635
I have the following lines of code in my web page - demo/example.
HTML:
<button class="wrong-answer" onclick="showResult(this)">42</button>
<button class="right-answer" onclick="showResult(this)">43</button>
<p id="answer"></p>
JS:
function showResult(b) {
var res = document.getElementById('answer');
if (b.classList.contains('right-answer')) {
res.innerHTML = '<span class="right">right</span>';
}
else {
res.innerHTML = '<span class="wrong">wrong</span>';
}
}
How can I make the <span>
tags appear or fade-in (with a duration of 2 seconds) when one of the buttons is selected, display this result (for a duration of 5 seconds) then if possible, removing it again (a duration of 2 seconds)?
Upvotes: 0
Views: 1409
Reputation: 8181
So, here is another solution with vanilla JS and CSS3. I haven't put in unnecessary details about the code as it's straightforward.
function showResult(b) {
var res = document.getElementById('answer');
if (b.classList.contains('right-answer')) {
res.innerHTML = '<span class="right">right</span>';
} else {
res.innerHTML = '<span class="wrong">wrong</span>';
}
res.classList.remove("hidden");
res.classList.add("visible");
setTimeout(function() {
res.classList.add("hidden");
}, 5000);
}
.visible {
visibility: visible;
opacity: 1;
transition: opacity 2s linear;
}
.hidden {
visibility: hidden;
opacity: 0;
transition: visibility 0s 2s, opacity 2s linear;
}
<button class="wrong-answer" onclick="showResult(this)">42</button>
<button class="right-answer" onclick="showResult(this)">43</button>
<p id="answer" class="hidden"></p>
Upvotes: 1
Reputation: 2272
Here's a fiddle. I added jQuery in my solution for easier coding, but you can do the same logic without it.
HTML:
<button data-answer="wrong">42</button>
<button data-answer="right">43</button>
<p id="answer">
<span class="wrong">wrong</span>
<span class="right">right</span>
</p>
CSS
p#answer span {display:none;}
JS
var timeout = 0;
$('button').click(function(){
clearTimeout(timeout);
$('p#answer span').hide();
$('p#answer span.' + $(this).data('answer')).fadeIn(2000);
timeout = setTimeout(function(){$('p#answer span').fadeOut()},7000);
});
Upvotes: 1
Reputation: 4224
You can do this by using jquery:
function showResult(b) {
var res = document.getElementById('answer');
if (b.classList.contains('right-answer')) {
res.innerHTML = '<span class="right">right</span>';
$("#answer").fadeIn(2000).fadeOut(3000);
}
else {
res.innerHTML = '<span class="wrong">wrong</span>';
$("#answer").fadeIn(2000).fadeOut(5000);
}
Upvotes: 0
Reputation: 3341
Here's the same thing done but using CSS classes more than JS/jQuery transitions: https://jsfiddle.net/x2fgbjbq/
The key thing in this example is:
transition: opacity 2s;
I've also changed how the code uses the <span>
. This is just personal preference - I try not to add/remove DOM elements on the fly if I can help it and instead just use what's already been created.
Upvotes: 0