Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't seem to get jquery resize event to work on Modernizr media query function

I'm trying to activate a resize event on the following function:

$(function() {
if (Modernizr.mq('only screen and (min-width: 1140px)')) {
$('div#ss1').html('<div>[snip]</div>');
$('div#ss1').append('<div><gcse:searchbox-only></gcse:searchbox-only></div>');
  } 
if (Modernizr.mq('only screen and (max-width: 1139px)')) {
$('div#ss2').html('<div>[snip]</div>');
$('div#ss2').append('<div><gcse:searchbox-only></gcse:searchbox-only></div>');
  } 
});

I wanted to add a resize listener to it. Based on http://api.jquery.com/resize/ I changed the first line to $(window).resize(function() but then the whole function stopped working.

What am I doing wrong? Thanks.

UPDATE: Based on this Paul Irish post I added smartresize to my plugins.js. I changed the function call from $(function() to $(window).smartresize(function() and it stopped working. Changing it back to $(function() and it worked again. Why can't I add a resize event listener of any type to this sucker? :-)

like image 729
Ian Avatar asked Jan 13 '23 12:01

Ian


1 Answers

The key point to understand here is what $(function() {}) is doing. The code inside of it isn't executing until the document is ready. Putting code in it is equivalent to putting code in this:

$(document).ready(function () { 
    //here 
})

You want to put your resize event inside of $(function() {}), like this:

function checkMq() {
    if (Modernizr.mq('only screen and (min-width: 1140px)')) {
        $('div#ss1').html('<div>[snip]</div>');
        $('div#ss1').append('<div><gcse:searchbox-only></gcse:searchbox-only></div>');
    } 
    if (Modernizr.mq('only screen and (max-width: 1139px)')) {
        $('div#ss2').html('<div>[snip]</div>');
        $('div#ss2').append('<div><gcse:searchbox-only></gcse:searchbox-only></div>');
    } 
}

$(function() {
    // the call to checkMq here will execute after the document has loaded
    checkMq();

    $(window).resize(function() {
        // the call to checkMq here will execute every time the window is resized
        checkMq();
    });

    // you can add other listeners here click, hover, etc.  
});

If you just have the $(window).resize(function() {}) without using $(function() {}), it won't work because the document isn't ready to be worked on yet, nor is it ready to have any event listeners added.

like image 68
natchiketa Avatar answered Jan 30 '23 20:01

natchiketa