Reputation: 187
$(window).on("load resize", function () {
if ($(window).width() < 768) {
menuHeight = '0px';
contactHeight = '100%';
} else {
menuHeight = ($('#desktop-menu').height() + 'px').toString();
contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
}
});
I want to access these two variables (menuHeight, contactHeight) outside of this function to be used elsewhere. I'm measuring the top height for a modal, but wan't it to be responsive on resize, not just load (it seems a simple If/Else would work in that case.) I might need some schooling on scope here. Thanks!!
Upvotes: 0
Views: 27
Reputation: 1671
You need to define them before:
var menuHeight = '';
var contactHeight = '';
$(window).on("load resize", function () {
if ($(window).width() < 768) {
menuHeight = '0px';
contactHeight = '100%';
} else {
menuHeight = ($('#desktop-menu').height() + 'px').toString();
contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
}
});
You can use a function:
function scroll() {
var menuHeight;
var contactHeight;
if ($(window).width() < 768) {
menuHeight = '0px';
contactHeight = '100%';
} else {
menuHeight = ($('#desktop-menu').height() + 'px').toString();
contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
}
getHeight(menuHeight,contactHeight)
}
function getHeight(menuHeight,contactHeight) {
console.log(menuHeight,contactHeight)
}
$(window).scroll(scroll);
For global access (not recommend)
window.menuHeight = '';
window.contactHeight = '';
Upvotes: 0
Reputation: 1074355
You define them outside the function. Also, since load
happens fairly late in the page load process, you'll want to proactively initialize them, then update them in response to load
and resize
. That suggests you want a reusable function:
var menuHeight; // Defining...
var contactHeight; // ...them
grabHeights(); // Proactive
$(window).on("load resize", grabHeights); // And on events
function grabHeights() {
if ($(window).width() < 768) {
menuHeight = '0px';
contactHeight = '100%';
}
else {
menuHeight = ($('#desktop-menu').height() + 'px').toString();
contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
}
}
If your code isn't already in a scoping function, you probably want to put it in one:
(function() {
var menuHeight;
var contactHeight;
grabHeights();
$(window).on("load resize", grabHeights);
function grabHeights() {
if ($(window).width() < 768) {
menuHeight = '0px';
contactHeight = '100%';
}
else {
menuHeight = ($('#desktop-menu').height() + 'px').toString();
contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
}
}
})();
...since globals are a Bad Thing™. :-)
You'll see people telling you to just go ahead and hook the event, then trigger it manually:
$("selector").on("event", function() {
// ...
}).triger("event");
I'm not a fan. If you need to call a function, just call it.
Upvotes: 2