Here are a few solutions for when the onclick
function is trying to access out-of-scope data.
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 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.
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.