4

The jquery .css method does not work for this. Is there an alternate one to get the real value in the css sheet like a percentage ect... ? Here is an example which show that .css don't work for this: External css:

margin-left: 10%;

Js Code:

var Marginleft = $(domElem).css('margin-left');
alert(Marginleft);

This return a value in pixel. I'd like to get the percentage, is it possible without going in the css as a string ?

  • Take a look if this can point you to the right direction: http://stackoverflow.com/a/4926651/961695 – Yuriy Galanter Oct 18 '13 at 20:22
  • You need something like [this](http://stackoverflow.com/a/17454470/1169519)? Though the snippet behind the link is actually changing a value in a stylesheet, you can develope it further to just read a value instead. – Teemu Oct 18 '13 at 20:34
  • why make simple when you can make complicate ? just add a class `ispercentage` to you nodes with margin 10% or whatever you want to call it, then check with `.hasClass('ispercentage')` ... – mikakun Oct 19 '13 at 05:12

2 Answers2

0

I do not think there is a built-in function for this. I'm not sure what you mean by "going in the css as a string," but you could easily calculate the percentage.

var percent = (parseFloat(Marginleft)/parseFloat($(domElem).parent().css('width')) * 100) + '%';
alert(percent);
Finni McFinger
  • 226
  • 4
  • 14
  • Unfortunately, this way of getting the percentage is useless for me, as my app need to know if the attribute had a percentage value in the css style sheet, and not it's current percentage... – user2888453 Oct 18 '13 at 21:07
0

Try this (Webkit only: Chrome, Opera, Safari)

var Marginleft = window.getMatchedCSSRules(domElem)[0].style["margin-left"]
alert(Marginleft);

This example would read "margin-left" style property from the first assigned class to the dom element. If you have multiple classes - you may have to loop thru the array to get the class you're intested in.

Demo: http://jsfiddle.net/rkT5Q/

For Gecko alternative take a look at https://gist.github.com/ydaniv/3033012

For a possible cross-browser one at https://stackoverflow.com/a/4926651/961695

Community
  • 1
  • 1
Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136