For some reason, I'm not understanding the scope of local and global variables with relation to jQuery click handlers. When I click the buttons, I'm getting "undefined", but I expect it to show the category of the button clicked. How do I address this?
I've setup an example to show my confusion. Fiddle here: http://jsfiddle.net/zvhsqeyn/
Simple html buttons:
<button class="hobbies">hobbies</button>
<button class="sledding">sledding</button>
<button class="personal">personal</button>
<button class="food">food</button>
Some javascript to handle the event where the buttons are clicked.
var GLOBAL_CATEGORIES = ['hobbies', 'sledding'];
$(window).load(function() {
var categories = ['personal', 'food'];
// local categories
for (var i = 0; i < categories.length; i++) {
$('.' + categories[i]).click(function() {
alert(categories[i]);
return false;
});
}
// Global categories
for (var i = 0; i < GLOBAL_CATEGORIES.length; i++) {
$('.' + GLOBAL_CATEGORIES[i]).click(function() {
alert(GLOBAL_CATEGORIES[i]);
return false;
});
}
});
Edit: After taking in the feedback, here is the properly working http://jsfiddle.net/zvhsqeyn/1/