tags:

views:

41

answers:

4

Hello,

I have an element with a class, the class has a set width. Later I change the width with $('#elm').width(100); now, even later, I want to go back to the original value. Is there a way to get what the original value is from the class definition itself rather than store a bunch of globals with the values I need.

Thanks, Justin

A: 

Not from the same element on which you've explicitly set the width through JS; but you could create a new element, give it the class and see what width it gets.

Example:

$('#elem').width(100);
alert($('#elem').width()); // this will return 100, no matter what width #elem was before
$('body').add('<div class="someclass" id="elem2"></div>');
alert($('#elem').width()); // this may return the width as assigned in CSS to .someclass
Piskvor
You can't get it with `$('#elem').width()`?
jasongetsdown
You can, but then you'll get the new, modified, width. Added example.
Piskvor
+3  A: 

Why not declare the modified width to another class, which you can then toggle, instead of using explicit values in you javascript?

nikc
the width changes based on the surrounding elements, its not a set width I can predetermine.
Justin808
Then perhaps you need a better grid system.
nikc
+1  A: 

I'd suggest nikc's answer, but you could always do $('#elm').removeAttr("style"); if you want to wipe any styles your scripts have added, and return them to the CSS values you've specified.

Really, though, you should be leaving the styling out of the code and just adding, removing and toggling various classes.

Malabar Front
Removing the style works best. The original value was percent based so getting the exact value from an newly added element would have been a bit more complex. The only style that is changing is the width so removing the attribute cleared it.
Justin808
+2  A: 

You COULD use the .data() to store the original and then restore the original values from there rather than use global values - it associates them that way.

Mark Schultheiss