Skip to content

Instantly share code, notes, and snippets.

@astout
Created October 7, 2018 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astout/78f0e8f8ee66b28056c31bfbaf895d64 to your computer and use it in GitHub Desktop.
Save astout/78f0e8f8ee66b28056c31bfbaf895d64 to your computer and use it in GitHub Desktop.
Thinkful JS Response

JavaScript

Hi student,

Sure! This is actually a pretty common problem that everyone encounters at some point in web development. This is what is known as a "scope" issue. Scope is essentially the environment that is known to the software at a given time of execution. What is happening in your example, is that when your onclick function is executed, it's a different scope than the prizes and btnNum variables. By the time the onclick executes, prizes and btnNum are long gone. The onclick function doesn't "know" about these variables. These variables are out of the scope of the onclick function.

So to fix this, there are a few things you can do. I've written about a few of the other methods that could be used in some further reading, but for simplicity I only included the solution I would recommend here.

Set onclick Function on HTML elements

This is what I would consider the cleanest solution. You won't need to loop through your HTML elements in javascript to apply the onclick function. Instead, you define a function in javascript, and just assign it on the HTML element.

<button id="btn-0" onclick="getPrize(0)">Button 1!</button>

Then you can define the getPrize function in your javascript and use the provided index to get the prize text.


Again, the main thing to keep in mind is ensuring all the variables you're trying to access at the time a line of code executes are still in scope.

I'm glad to clarify further. If you still wind up stuck, just let me know. Good luck!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment