Skip to content

Instantly share code, notes, and snippets.

@astout
Created October 7, 2018 19:36
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/cd09a40bdcb1bf37ffd506e962bc7250 to your computer and use it in GitHub Desktop.
Save astout/cd09a40bdcb1bf37ffd506e962bc7250 to your computer and use it in GitHub Desktop.
Thinkful JS Further Reading

JavaScript (further reading)

Here are a few solutions for when the onclick function is trying to access out-of-scope data.

Function Returns A Function

This one is probably the most confusing, but functions that return functions is a common practice in JavaScript, so it's something you'll want to get familiar with. You can create a function that knows the full scope of what you need and returns a unique function that calls the alert with a given text.

function getPrizeFunction(prizeText) {
  return function() {
    alert(prizeText);
  }
}

The getPrizeFunction itself does not call the alert method. Instead getPrizeFunction returns an anonymous function that when called will call alert with the provided prizeText. You can store a function in a variable.

var prizeText = 'A Unicorn!';
var prizeFunction = getPrizeFunction(prizeText);

So prizeFunction here is a variable storing an anonymous function that will call alert(prizeText).

Data Attributes

Data Attributes help provide data to handle scope for HTML DOM elements. You can apply data to elements and use this data when an event is fired.

<button id="btn-0" data-index="0">Button 1!</button>

Then you can access the element's properties using the this keyword and you can access the data attributes via this.dataset.

So when the onlick function executes, you can access a property of the element to get the index of the prizes array. One thing to keep in mind in this solution is to ensure your prizes array is defined in the scope of the onclick function.

Define onclick Function in HTML

This is probably 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.


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.

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