Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a javascript set style property to CSS default

Tags:

I'm trying to work out how, after changing style properties with javascript, I can revert to the value in the stylesheet (including the units).

In the example below, I'd like the output to read 100px (the value in the CSS), rather than 10px, as getComputedStyle gives.

I'd also keep the dummy div at top:25px, so removing the style property won't work.

The best I have is cloning the node and reading the height and storing in a property (http://jsfiddle.net/daneastwell/zHMvh/4/), but this is not really getting the browser's default css value (especially if this is set in ems).

http://jsfiddle.net/daneastwell/zHMvh/1/

<style>  #elem-container{    position: absolute;    left:     100px;    top:      200px;    height:   100px;  } </style>  <div id="elem-container">dummy</div> <div id="output"></div>    <script>   function getTheStyle(){     var elem = document.getElementById("elem-container");     elem.style.left = "10px";     elem.style.top = "25px";     var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("left");     document.getElementById("output").innerHTML = theCSSprop;    }   getTheStyle(); </script> 
like image 944
Dan Eastwell Avatar asked May 22 '12 09:05

Dan Eastwell


People also ask

How do I restore the default property value in CSS?

In short, there's no easy way to restore to default values to whatever a browser uses . The closest option is to use the 'initial' property value, which will restore it to the default CSS values, rather than the browser's default styles.

Can we change CSS property using JavaScript?

With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.

What is revert in CSS?

The revert CSS keyword reverts the cascaded value of the property from its current value to the value the property would have had if no changes had been made by the current style origin to the current element.


2 Answers

Just clear the inline style you wish to fallback to original stylesheet on.

elem.style.left = null; 
like image 154
abaelter Avatar answered Sep 21 '22 19:09

abaelter


The style object has a built-in removeProperty() method, so you could do something like:

elem.style.removeProperty('left'); 

As far as I know, this will have exactly the same effect as setting the property to null, as abaelter suggested. I just thought it might be worth including for the sake of completeness.

like image 39
DoctorDestructo Avatar answered Sep 20 '22 19:09

DoctorDestructo