valor metodo funcion eventos evento detectar change capturar cambios cambio cambiar agregar jquery resize modernizr

jquery - metodo - funcion on change



Parece que el evento de cambio de tamaño de jquery no puede funcionar en la función de consulta de medios de Modernizr (1)

Estoy intentando activar un evento de cambio de tamaño en la siguiente función:

$(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>''); } });

Quería agregarle un oyente de cambio de tamaño. Basado en http://api.jquery.com/resize/ Cambié la primera línea a $(window).resize(function() pero luego toda la función dejó de funcionar.

¿Qué estoy haciendo mal? Gracias.

ACTUALIZACIÓN: Basado en este post de Paul Irish, agregué smartresize a mis plugins.js. Cambié la llamada de función de $(function() a $(window).smartresize(function() y dejó de funcionar. Volver a cambiar a $(function() y funcionó de nuevo. ¿Por qué no puedo agregar un evento de cambio de tamaño? oyente de cualquier tipo a este lechón? :-)


El punto clave para entender aquí es lo que está haciendo $(function() {}) . El código dentro de él no se está ejecutando hasta que el documento esté listo. Poner código en él es equivalente a poner código en esto:

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

Desea poner su evento de cambio de tamaño dentro de $(function() {}) , así:

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. });

Si solo tiene $(window).resize(function() {}) sin usar $(function() {}) , no funcionará porque el documento aún no está listo para trabajar, ni tampoco listo para agregar cualquier oyente de evento.