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
  • 197,815
  • 30
  • 248
  • 265
Zach
  • 422
  • 1
  • 5
  • 12

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,188
  • 10
  • 59
  • 102
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,543
  • 2
  • 25
  • 31