Montin
Montin

Reputation: 45

JQuery FadeIn not working with JS button click

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');
    
  });
});

Upvotes: 1

Views: 45

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337570

Your code doesn't work for 2 reasons.

  1. You didn't include jQuery.js in the page
  2. The #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>

Upvotes: 1

Related Questions