Home > Software engineering >  Onclick function is returning reference error
Onclick function is returning reference error

Time:10-16

This seems like it should be basic, but I can't figure out why it's happening. I'm getting an uncaught reference error trying to use a javascript function in html.

I've created a button that will generate a new quote, using a randomQuote function I created (codepen for in context: https://codepen.io/cpmcclure/pen/MWvKaVp):

note: I couldn't figure out how to add jquery into this example, but it is included in the codepen

// create array for quotes
let quoteList = [];

// retrieve quotes and assign them to quoteList array
const settings = {
  "async": false,
  "crossDomain": true,
  "url": "https://type.fit/api/quotes",
  "method": "GET"
}

$.ajax(settings).done(function (response) {
  const data = JSON.parse(response);
  quoteList = data;
});

// create display quote variable
let displayQuote = {};

// function to assign random quote to displayQuote on a click event
function randomQuote() {
   displayQuote = quoteList[Math.round(Math.random() * 1643)];
}
<button id="new-quote" onclick="randomQuote()">New Quote</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I've looked at other pens that use this same syntax to access a js function in the html, any idea what I'm doing wrong?

I know I'm getting the quotes in properly, and if I call randomQuote in the JavaScript, it does what it's supposed to do, it seems I'm having an issue getting the html and js to communicate.

CodePudding user response:

This is probably because you are using jquery for ajax and you haven't added the library in your code.

{
  "message": "Uncaught ReferenceError: $ is not defined",
  "filename": "https://stacksnippets.net/js",
  "lineno": 23,
  "colno": 1
}
  • Related