I have this simple code that generates a random number from 0-3 and upon clicking the button the generated number appears in the div. I tried making it fade in using JQuery but it's not working. jsfiddle https://jsfiddle.net/Montinyek/3cj7nbop/27/
function random() {
let number = Math.floor(Math.random() * 3);
let result = ""
switch(number) {
case 0:
result = "Zero";
break;
case 1:
result = "One";
break;
case 2:
result = "Two";
break;
case 3:
result = "Three";
}
return result;
}
function final() {
document.addEventListener("click", function(){
document.getElementById("div").innerHTML = random();
});
}
$(document).ready(function(){
$("button").click(function(){
$("#div").fadeIn('slow');
});
});
Your code doesn't work for 2 reasons.
#div wasn't hidden to start with.Also note that you should avoid the onclick and other event related attributes as they are not good practice. As you're using jQuery anyway, the logic which updates the HTML of the div can be moved in to there. Try this:
function random() {
let number = Math.floor(Math.random() * 3);
let result = ""
switch (number) {
case 0:
result = "Zero";
break;
case 1:
result = "One";
break;
case 2:
result = "Two";
break;
case 3:
result = "Three";
}
return result;
}
$(document).ready(function() {
$("button").click(function() {
$("#div").html(random()).fadeIn('slow');
});
});
#div {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<button>Click me</button>
<div id="div"></div>