mercredi 8 juillet 2020

How to solve Uncaught TypeError: Cannot read property '0' of undefined for random quote generator?

I have a random quote generator snippet of jQuery code, which is giving me the following console error:

When I click the button it shows the first quote successfully, but then stops.

Here is my code:

jQuery(document).ready(function(){
      jQuery("#change").click(function(){
var quotes = [
  ["It Crowd" ],
  ["Black Books"],
  ["Still Game"],
  ["quote 4"],
];
  // generate random integer< array.length
var number = Math.floor(Math.random()* (quotes.length+1));
//get the elements or just put them in the document write below
var showQuotes = quotes[number][0];
        
  //                      
  jQuery("#quotecontent").fadeOut("medium",function(){
           var newer = jQuery(
             '<div id="content"><p id="quote">'  + showQuotes + '</p></div>' ); 
        jQuery(this).replaceWith(newer);
      jQuery('#quotecontent').fadeIn("medium");
      });                          
      });    
});

Here is the HTML

<div id="quotecontent">
<p id="quote">This is the original quote</p>
</div>
 <div id="btn-container">
<button id="change">Press</button>
      </div>

And this is the error message:

Uncaught TypeError: Cannot read property '0' of undefined

I know it relates to this part of the code:

var showQuotes = quotes[number][0];

But I am just unsure why it wouldn't be working as I am a bit new to arrays. If someone could kindly help me to understand why this isn't working, that would be so appreciated!!!

Codepen if it helps: https://codepen.io/kiaramelissa/pen/XWXqgVa




Aucun commentaire:

Enregistrer un commentaire