1

I am currently trying to save the original CSS values of an element in an object like so:

var xc = {
    "pos": {
        "ml": String($(this).css("margin-left")),
        "mt": String($(this).css("margin-top"))
    }
};

After the values stored, I then change the CSS styles of the element whose values I just stored.

When I try to access the original values from the object, I am returned the new CSS styles of the element.

For example, 235px is stored in the object, I then change the 235px of the element to 10px. The 235px of the element now becomes 10px.

j08691
  • 204,283
  • 31
  • 260
  • 272
Zach
  • 442
  • 1
  • 5
  • 12
  • I think you want to clone an object. http://stackoverflow.com/a/122704/2166409 – Daniel Kmak Nov 10 '13 at 21:11
  • 2
    What is your question? – gdoron Nov 10 '13 at 21:11
  • 4
    _"When I try to access the original values from the object, I am returned the new CSS styles of the element."_ Please, **please** show us how you're (1) changing the CSS of the element and then (2) trying to access the original values. – Matt Ball Nov 10 '13 at 21:12
  • Also consider using [this overload](http://api.jquery.com/css/#css-propertyNames) – gdoron Nov 10 '13 at 21:17
  • Also, why that weird `String`? jQuery's css function returns a... string! – gdoron Nov 10 '13 at 21:17

2 Answers2

4

You can easily preserve the style values by attaching them to a jQuery selection using .data()

var $ele = $('#ele');
$ele.data( $ele.prop('style') );

If you change the css of $ele, but want to access the original values, it would just be a matter of calling $ele.data()[property].

For example, if you want to revert all CSS values to their original values, then you could just simply pass the object saved in data to .css():

$ele.css( $ele.data() );
Wex
  • 15,539
  • 10
  • 64
  • 107
0

Try this (just without String):

<!DOCTYPE html>
<html>
<head>
  <script data-require="jquery@1.9.1" data-semver="1.9.1" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
  <div style="margin-left: 10px; margin-top: 20px;"
    onclick="var xc = {'pos': {'ml': $(this).css('margin-left'), 'mt': $(this).css('margin-top') } }; alert(xc.pos.ml + ' ' + xc.pos.mt);">Test</div>
</body>
</html>

Plunker example

lukpaw
  • 1,603
  • 2
  • 26
  • 31