Reputation: 19
I have a variable that's supposed to store the data-filter
of what has just been clicked. It only works inside one of my click
events though, and stops working when it is moved outside of that event. I want to make it global so that I can access it anytime, but I don't understand jQuery well enough to know what the issue is.
$(document).ready(function () {
var filterValue = $(this).attr('data-filter');
//Function Doesn't work when var filterValue is located here.
$('nav').on('click', 'a', function () {
//This function works when var filterValue is located here.
$('nav').find('.is-checked').removeClass('is-checked');
$(this).addClass('is-checked');
if ($(this).data('filter') === 'home') {
$('main').find('.dim').removeClass('dim', 500);
} else {
$('.cell')
.not('.' + filterValue)
.addClass('dim', 500);
$('main')
.find('.' + filterValue)
.removeClass('dim', 500);
}
});
$('main').on('click', filterValue, function () {
//This function does not work when var filterValue is located here.
console.log(filterValue);
});
});
Upvotes: 1
Views: 178
Reputation: 357
Inside of the function, this is in a different scope (Local). If you want to use the same scope, you should assign the first scope to a new variable called that or something else.
function someFunc() {
var that = this;
something.on("click", function() {
console.log(that);
});
};
Upvotes: 1