Luke Wenke
Luke Wenke

Reputation: 1138

Retrieving original stylesheet CSS property value in JQuery/Javascript

I know that the original css value from the style sheet can be assigned using: $('#id').css('property', ''); but is there a way to retrieve the value without changing the property in the object? Note that may be different from retrieving the current value because it may have changed from the style sheet value.


Possible "solutions" (untested)

var originalTopPos = $("#testPic").css("top");
....
$("#testPic").animate({"top": originalTopPos + "px"},"slow");

I'm using many images though... so it is a bit more complicated than that.


(I want to animate it from the current to original value, not just jump from one value to the other)

var currentTopPos = $("#testPic").css("top");
var originalTopPos = $("#testPic").css("top", "").css("top");
$("#testPic").css("top", currentTopPos + "px")
$("#testPic").animate({"top": originalTopPos + "px"},"slow");

Upvotes: 6

Views: 8114

Answers (5)

Anthony
Anthony

Reputation: 11

The easiest way to do this depends on whether you want to push the current value or the original. Since you say original, the surest way is to (if you're using JQuery) create a script within $(document).ready(...) that executes first and stores values for everything to variables.

The second way is to do $(this).css("style-name","") (the null argument resets to default).

If you are simply pushing the current value, you can do the similar thing with the variables. myVar = $(this).css("style-name") returns the current attribute value. Do not do var myVar = .... Its just myVar. My browser yelled at me about that.

Upvotes: 1

Luke Wenke
Luke Wenke

Reputation: 1138

I found the answer....

$(this).attr("customAttributeName", $(this).position().top);

then you can recall it with:

$(this).attr("customAttributeName");

Upvotes: 3

etoxin
etoxin

Reputation: 5294

is this what your looking for?

<html>
<head>
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        newColor = $('#id').css('color');
        $('#newid').css('color',newColor);
        $('#id').css('color','green');
    });
    </script>
    <style type="text/css" media="screen">
    #id{color:red;}
    </style>
</head>
<body>
<div id="id"><h1>Boom!</h1></div>
<div id="newid"><h1>Boom!</h1></div>
</body>
</html>

Upvotes: 0

Sparkup
Sparkup

Reputation: 3754

This will return 'none'

<div id="test" style="display:none;"></div>

var property = $('#test').css('display');
alert(property);

Upvotes: 0

Jeremy
Jeremy

Reputation: 5433

Assuming I understand the question, you just want something like object.style.property, no need for jQuery.

Upvotes: -2

Related Questions