It seems I can’t get the jquery resize event to work with the Modernizr media recording function

I am trying to fire a resize event for 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 post by Paul Irish, I added smartresize to my plugins.js. I changed the function call from $(function() to $(window).smartresize(function() and stopped working. Changing it to $(function() , it worked again. Why can't I add a resize event listener of any type to this suction cup ?:-)

+4
source share
1 answer

The key to understanding here is what $(function() {}) does. The code inside it is not executed until the document is ready. Entering the code in it is equivalent to putting the code in this:

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

You want to place the resize event inside $(function() {}) , for example:

 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 only have $(window).resize(function() {}) without using $(function() {}) , this will not work, because the document is not ready to work, and it will not be ready to add listeners events.

+9
source

All Articles