Adi
Adi

Reputation: 4022

passing a global javascript variable into jquery plugins on resize

I am creating a mobile first responsive web site that has a few custom jquery plugins which kick in at certain breakpoints.

First, snippets of the code, and then ill explain the issue...

CSS:

@media (min-width: 20em) {
  html:after {
    content: "320";
     } }
@media (min-width: 25em) {
  html:after {
    content: "400";
     } }
@media (min-width: 30em) {
  html:after {
    content: "480";
     } }

GLOBAL JS

var FOO = {
 mq: function() {
   return  parseInt(window.getComputedStyle(document.documentElement,':after').getPropertyValue('content').replace(/['"]/g,''),10);                     
 }
}

JQUERY PLUGIN 1

this.init = function()
{
 $(window).on("load resize orientationchange", function() {
   if(FOO.mq() >= 480) {
      DO SOMETHING
   }
});
};

JQUERY PLUGIN 2

this.init = function()
{
 $(window).on("load resize orientationchange", function() {
   if(FOO.mq() >= 560) {
      DO SOMETHING ELSE
   }
});
};

Now the problem with putting the FOO.mq() in the jquery plugin is that it will fire the FOO.mq() function for every DOM object found (e.g. if the plugin does something to 10 images it will fire the FF.mq() 10 times) where really thats not needed as we only need to check once.

I have tried putting the resize/return value in a global object but it nevers seems to work and gets picked up bu the jquery plugins.

Any pointers would be greatly appreciated.

Thanks

Upvotes: 0

Views: 734

Answers (2)

Alnitak
Alnitak

Reputation: 339965

Assuming that this calculated value only changes on document load, or if the window changes layout:

var FOO = FOO || {};      // create global namespace obj, if required
$(function() {
    var mq;               // scoped variable

    // catch events that might change the @media CSS rules
    $(window).on("load resize orientationchange", function() {
        mq = parseInt(window.getComputedStyle(document.documentElement,':after').getPropertyValue('content').replace(/['"]/g,''),10);
    });

    FOO.mq = function() { // function that just returns the scoped variable
        return mq;
    }
});

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74420

Try to use a timeout:

this.init = function () {
    var timeout;
    $(window).on("load resize orientationchange", function () {
        clearTimeout(timeout);
        timeout = setTimeout(function(){
           if (FOO.mq() >= 480) {
               DO SOMETHING
           }
        },15);//even 0 should be enough
    });
};

Upvotes: 0

Related Questions