How can I increase the width of an element by 10rem using jquery. Issue is Jquery always return width/height in pixels and we want to update the height/width in some other units.
Example on: JS Bin
var $c = $('#container');
console.log($c.width());
var c = document.getElementById('container');
// Q1. Why is it different from above one. This is 324 while earlier it was 320. See the output.
console.log(c.clientWidth);
// Q2. How to update the code to increase the width by 10rem.
$c.css({width: $c.width() + 10}); //It adds 10 pixels here.
console.log($c.width());
My questions are comments in the code.
jQuery width() Method The width() method sets or returns the width of the selected elements. When this method is used to return width, it returns the width of the FIRST matched element. When this method is used to set width, it sets the width of ALL matched elements.
Rem (short for “root-em”) units dictate an element's font size relative to the size of the root element. By default, most browsers use a font size value of 16px. So, if the root element is 16px, an element with the value 1rem will also equal 16px.
The difference between . css( "width" ) and . width() is that the latter returns a unit-less pixel value (for example, 400 ) while the former returns a value with units intact (for example, 400px ).
The jQuery outerWidth() and outerHeight() methods get or set the outer width and the outer height of the element respectively. This outer width and height includes padding and border but excludes the margin on the element.
Decided to post an updated answer using jquery. You can call the function without a parameter to get the number of pixels in one rem, or you can pass in a count for rem to get the number of pixels in that many rem. Here's a jsFiddle also: http://jsfiddle.net/drmyersii/mr6eG/
var rem = function (count)
{
var unit = $('html').css('font-size');
if (typeof count !== 'undefined' && count > 0)
{
return (parseInt(unit) * count);
}
else
{
return parseInt(unit);
}
}
I suppose that taking the font-size
of the html
element will give you the rem
, using a function, you'll be able to retrieve it even if it changes:
// This Function will always return the initial font-size of the html element
var rem = function rem() {
var html = document.getElementsByTagName('html')[0];
return function () {
return parseInt(window.getComputedStyle(html)['fontSize']);
}
}();
// This function will convert pixel to rem
function toRem(length) {
return (parseInt(length) / rem());
}
example: http://jsfiddle.net/4NkSu/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With