Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/JavaScript: convert pixels to em in a easy way

Tags:

I am looking for a easy way to add a line of code to a plugin of mine, to convert a couple of pixel values into em values, because the layout of my project needs to be in ems. Is there an easy way to do this, because I don't want to add a third-party plugin to the site.

Won't post the code here, as it has nothing to do with the plugin it self.

Thanks.

Example: 13px -> ??em

like image 985
user759235 Avatar asked Apr 24 '12 21:04

user759235


People also ask

How many pixels is 1em?

So, by default 1em = 16px, and 2em = 32px.


1 Answers

I think your question is very important. Since the classes of display resolutions are rapidly increasing, using em positioning to support wide range of screen resolutions is a really appealing approach. But no matter how hard you try to keep everything in em -- sometimes you get a pixel value maybe from JQuery drag and drop or from another library, and you would want to convert this value to em before sending it back to server for persistence. That way next time user looks at the page, item would be in correct position -- regardless of screen resolution of the device they are using.

JQuery plugins are not very scary when you can review the code, specially if they are short and sweet like this plugin to convert pixel values to em as you want. In fact it is so short I will paste the whole thing here. For copyright notice see the link.

$.fn.toEm = function(settings){     settings = jQuery.extend({         scope: 'body'     }, settings);     var that = parseInt(this[0],10),         scopeTest = jQuery('<div style="display: none; font-size: 1em; margin: 0; padding:0; height: auto; line-height: 1; border:0;">&nbsp;</div>').appendTo(settings.scope),         scopeVal = scopeTest.height();     scopeTest.remove();     return (that / scopeVal).toFixed(8) + 'em'; };   $.fn.toPx = function(settings){     settings = jQuery.extend({         scope: 'body'     }, settings);     var that = parseFloat(this[0]),         scopeTest = jQuery('<div style="display: none; font-size: 1em; margin: 0; padding:0; height: auto; line-height: 1; border:0;">&nbsp;</div>').appendTo(settings.scope),         scopeVal = scopeTest.height();     scopeTest.remove();     return Math.round(that * scopeVal) + 'px'; }; 

Usage Example: $(myPixelValue).toEm(); or $(myEmValue).toPx();.

I just tested this in my application, it works great. So I thought I share.

like image 50
Aras Avatar answered Sep 20 '22 01:09

Aras