Q:

Execute a jQuery function only over a specific width of window (even resizing)

I added this script to my website, in order to dinamically change color of text, based on background image.
I'm currently executing call to it on ready() with the following documented code:
$(document).ready(){
  BackgroundCheck.init({
    targets: '.target',
    images: '.thumbnails'
  });
});

and script, practically add a specific css class to objects with class "thumbnails"
My problem is that I don't want that this code is executed when width of the window is lower than 768px, either during loading of page, or resizing window under this value.
I thought about this code:
$(document).ready(){
   if(window.width() > 768 )
   {
      BackgroundCheck.init({
        targets: '.target',
        images: '.thumbnails'
      });
   }
});

but it is fired only at first loading.... instead I need that this script has no effect in ANY case under 768px of window width, and HAS effect in ANY case over 768px.
Please, how can I do that? Thank you.

A:

Is this what you want?
window.resize only fires when you indead resize the window so... you need to manually fire the script when you load the page.
The best way to do this is to wrap your code in a small function and fire that once (see below) then attach the resize event to the same function and voila.
http://jsfiddle.net/NKLd5/2/
// same as doc.ready, i prefer this over $(document).ready
$(function() {
    // variables ftw!
    var win = $(window);
    
    // fire it once on document.ready
    resizeHandler();
    
    // Fires on every resize   
    win.resize(resizeHandler);
    
    function resizeHandler() {
        if (win.width() >= 768) {
            BackgroundCheck.init({
                // etc
            });
        }
    }
});

if you only want to fire the script once, you can set a boolean that is set to true when the script fires for the first time.
Then in the resize handler
    var fired = false;
    ...

    function resizeHandler() {
        if (win.width() >= 768 && !fired) {
            fired = true;
            ...

MediaQueries
If you are only going to use the js for adding classes you should really use mediaqueries, unless you are doing some complex things.
/* applies this css to all elements with the .targets and .thumnails classes */
/* Everything below 768px */
@media all and (max-width: 767px) {
    .targets {
        background: blue;
    }
    .thumbnails {
        background: blue;
    }
}
/* everything > 768px */
@media all and (min-width: 768px) {
    .targets {
        background: red;
    }
    .thumbnails {
        background: red;
    }
}

