0

assuming I have a code that randomly selects an element in an array just as below, how will I make the next element fadeIn;

var textHolder = document.getElementById("text");
    var button = document.getElementById("btn");
    var arrayText = ["the King", "love don't cost a thing", "the programming guru", "a"];
 <h2 id="text">change me randomly</h2>
    <button id="btn">new random</button>
    
                    
    
    

this is the function that does the random text generator

var randomText = function(){
var randomNumber = Math.floor(Math.random()*arrayText.length);
textHolder.innerHTML = arrayText[randomNumber];
};

i itry to add fadin method here but the code stop work but when i remove the fade method it start working again, please what am i doing wrong.

button.addEventListener("click", function(){
textHolder.fadeOut();
randomText();
textHolder.fadeIn();
});
Nemus
  • 3,879
  • 12
  • 38
  • 57
  • 1
    There is no native JavaScript method as `fadeOut()` and `fadeIn()`, May be answer in http://stackoverflow.com/questions/6121203/how-to-do-fade-in-and-fade-out-with-javascript-and-css help – Satpal Apr 30 '17 at 11:13
  • fadeIn/Out basicly sets a special css class, that has a transition defined (and sets display obviously). So either use jQuery or search for css transitions and implement it on your own! – Jeff Apr 30 '17 at 11:16

1 Answers1

0

I think you could use jQuery to do that, and here's my code snippet

var textHolder = $("#text"); // See, you can type less
var button = $("#btn"); // Also here
var arrayText = ["the King", "love don't cost a thing", "the programming guru", "a"];

var randomText = function() {
  var randomNumber = Math.floor(Math.random() * arrayText.length);
  textHolder.text(arrayText[randomNumber]);
};

$(function() {
  // On click event
  button.click(function() {
    // Fade out the text holder
    textHolder.fadeOut(function() {
      // After that, display the random text
      randomText();
      // then, fade in the text holder
      $(this).fadeIn();
    });
  });
});
<!-- Here, I've included jQuery library to make it work. -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- Contents -->
<h2 id="text">change me randomly</h2>
<button id="btn">new random</button>
Xtravagant
  • 121
  • 8