What I'm trying to do is set a global variable dot type to "mobile" or "desktop" according to the screen size.
var userScreen = {}
if (screen is small){
userScreen.type === 'mobile'
}
else {
userScreen.type === 'desktop'
}
Everything is working within the same file but I'm having issues getting the userScreen.type to be available in another JavaScript file.
screen-size.js:
$(document).ready(function(){
var userScreen = {};
var resizeTimer;
$(window).on('resize load', function(e) {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
var windowWidth = $(window).width();
if ($('body').height() < $(document).height()) {
var windowWidth = windowWidth + 15;
}
if (windowWidth < 768){
userScreen.type = 'mobile';
}
else{
userScreen.type = 'desktop';
}
}, 250);
});
another-js-file
$(document).ready(function(userScreen){
console.log(userScreen.type);
});
Console Log "userScreen.type" result:
function( obj ) {
if ( obj == null ) {
return obj + "";
}
// Support: Android<4.0, iOS<6 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ t…
Load order:
- screen-size.js
- another-js-file.js
Thanks
EDIT
Want to say thank you for everyones responses. Final answer
So I created an IIFE with just setting the window.userScreen
object
get-user-screen.js
window.userScreen = {};
function getScreenSize(){
var windowWidth = $(window).width();
if ($('body').height() < $(document).height()) {
var windowWidth = windowWidth + 15;
}
if (windowWidth < 768){
userScreen.type = 'mobile';
}
else{
userScreen.type = 'desktop';
}
console.log(userScreen.type);
}
(function(){
getScreenSize();
}());
That made the variable available globally like I wanted and eliminated the Timeout issue that was brought up. Everything is working as expected.
Thanks again