jquery - How to most efficiently check for certain "breakpoints" upon browser re-size? -


i'm playing responsive design have 2 breakpoints defined:

mobile > max-width 320px tablet portrait > max-width 767px 

on desktop have lot of animation + advanced functionality going on javascript. on mobile , tablet im looking simplify , disable both js + "re-building" dom elements.

im wondering efficient way determine breakpoints (in terms of width) be? im thinking lot performance here.

i know can check window width upon re-size like:

$( window ).resize(function() {   if ($(window).width() > 320 && $(window).width() < 400) {     //mobile   }   if ($(window).width() > 401 && $(window).width() < 768) {     //tablet   }   if ($(window).width() > 769) {     //desktop   } }); 

but seems "expensive" operation?

any suggestions lightweight libraries can used welcome!

i ran problem , have not found perfect solution. however, there workaround seems less resource hungry. using timeout inside resize() function , clearing it, can make sure code run, once viewport has stopped resizing.

var resizetimer, width; var mobile = tablet = desktop = false;  $(window).resize(function() {     // clear timeout     cleartimeout(resizetimer);      // execute breakpointchange() once viewport      // has stopped changing in size 400ms     resizetimer = settimeout(breakpointchange(), 400); });  function breakpointchange() {     // use vanillajs window.innerwidth      // instead of jquery $(window).width() suggested simon     width = window.innerwidth;      if (!mobile && width < 400) {         tablet = desktop = false;         mobile = true;         console.log('is mobile');     }      if (!tablet && width > 401 && width < 768) {         mobile = desktop = false;         tablet = true;         console.log('is tablet');     }      if (!desktop && width > 769) {         mobile = tablet = false;         desktop = true;         console.log('is desktop');     } } $(window).resize(); 

this not best 1 can do, prevent code constantly being run. feel free add answer and/or correct me. here fiddle


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -