I'm using a jquery script called magnific popup and I'm trying to access a variable I created in a callback function, inside another callback function but I can't work out how to do it. My code for the magnific init looks like this:
$('.packery').magnificPopup({
delegate: '.js-modal',
type: 'ajax',
mainClass: 'mfp-zoom-in',
removalDelay: 500, //delay removal by X to allow out-animation
callbacks: {
elementParse: function(item) {
item.community = item.el.attr('data-community');
var communityClass = item.community;
console.log(item.community);
// this ^ does actually print the data-community
console.log('Parsing content. Item object that is being parsed:', item);
},
resize: function() {
console.log('Popup resized');
// resize event triggers only when height is changed or layout forced
$('.mfp-bg').addClass(communityClass);
}
}
});
If I try and set $('.mfp-bg').addClass(communityClass);
or $('.mfp-bg').addClass(item.community);
I get a Uncaught ReferenceError: communityClass is not defined.
I can't apply a class to mfp-bg inside elementParse as that element hasn't been created yet.
I know that I can't use variables from different functions in javascript, but I'm a bit stuck at this point on how I can actually use the data-community attribute inside the resize callback, because it seems like I can only create the variable inside the elementParse callback?
Any help would be much appreciated, cheers.
You could create a global variable, outside the function and assign item.community
to it. That way you will be able to access it in the other callback aswell
For example:
var communityClass;
$('.packery').magnificPopup({
delegate: '.js-modal',
type: 'ajax',
mainClass: 'mfp-zoom-in',
removalDelay: 500, //delay removal by X to allow out-animation
callbacks: {
elementParse: function(item) {
item.community = item.el.attr('data-community');
communityClass = item.community;
console.log(item.community);
// this ^ does actually print the data-community
console.log('Parsing content. Item object that is being parsed:', item);
},
resize: function() {
console.log('Popup resized');
// resize event triggers only when height is changed or layout forced
$('.mfp-bg').addClass(communityClass);
}
}
});