Obtaining the width of the viewport in jQuery is as simple as using $(window).innerWidth()
.
It is important to keep track of window resizing by using
$(window).resize( yourRedrawFunction )
Be cautious of converting pixels to em units. Width properties are typically in pixels, whereas you may require them in em units. This conversion can be challenging to calculate accurately, so it is advisable to avoid it if possible.
Here is a sample of it in action:
function redrawButton(){
var pxPerEm = 13, // <- adjust as needed
pxWidth = $(window).innerWidth(),
emWidth = Math.round( pxWidth / pxPerEm );
$('#btnSelectAll')[ width < emWidth ? 'hide' : 'show' ]();
return true;
}
redrawButton();
$(window).resize( redrawButton );
To calculate the em size, one method is to extract the root font-size
property from the CSS. However, this relies on the css property being present and correct. It might be safer to use a predetermined value, such as 13px as shown in my example.
var pxPerEm = /^(\d+)px$/.exec($(document.body).css('font-size')) ? Number(RegExp.$1) : 13;