February 29, 2012

how do you find the non-computed css width with JQuery

Question by coder

I know I can use .width() and .css('width') to get the computed width of an element, but how do I get the value that is set on the element for the width attribute? This is not the same value as the computed width and I need to know dynamically what the intended width is.

Answer by Starx

style attributes are changed, once you manipulate it using jQuery. So it cannot be retrieved later on. The best way, I think would be backing up at load if you need it.

$(function() {
   var backup = $("#element").attr("style");
   // do others
});

See this demo to get my point.

Later you can use .split() method to extract info like this

sp = backup.split(";");
$.each(sp, function(k,v) {
    var params = v.split(":");
    var att = params[0];
    var val = params[1];
    //alert(att+val);
});

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!