I just want to know how to use the jquery .css() function to not overwrite, but to add additional values to css properties.
For instance, I have an element that is currently has the css transform:translate(-50%, -50%)
on it. And I want to use the jQuery .css() function to ADD transform: rotate(90deg)
, but when I use it, it overwrites it.
Check out this fiddle if my description is confusing. http://jsfiddle.net/justinbchristensen/mvhwbjLo/1/
You will see in the Fiddle that when you first click the button, the square loses its original transformation, slides down, and rotates, but all subsequent clicks on the button simply rotate the square because it's not losing the 'transform:translate' property.
I don't want to have to say in my .css() function element.css('transform', 'translate(-50%,-50%) rotate(90deg)'
, I just want to be able to add the rotate to the existing transformation.
Is there any way to do this?
The reason that it overrides the value instead of adding to it is simply due to how the cascade works. Namely, you're setting a value on the
transform
property, which like all other CSS properties can only have one value at a time, therefore as far as the API is concerned you're overwriting its existing value with a new one. In CSS, this is what it might look like:As you can see, this will result in the second declaration overriding the first.
CSS does not support partial or additive property declarations, and likewise there is no way to directly add a value to an existing property without causing the existing value to be lost.
Essentially, this means you will have to include the existing transform in the new value when you set it. Since you are setting it using jQuery, you can retrieve the existing value using the
.css()
getter, then concatenate your new transform and apply the result, saving you the need to hardcode the existing value:The main problem with this is that triggering this particular block of code again will cause
currentTransform
to contain the rotation as well. This will continue adding rotations each time. If this is not desired, you will either need to write some checks, or failing that, unfortunately, hardcode the value.Save the current style, then concatenate:
http://jsfiddle.net/oqqubda8/
It works, and I don't know if there's another way to do it.
Since
transform
is kind of a shorthand, the values must be combined... There's no increment method.What you could do, is retrieve the previous value and append the new one:
Updated JsFiddle