Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing CSS Values with Javascript

It's easy to set inline CSS values with javascript. If I want to change the width and I have html like this:

<div style="width: 10px"></div> 

All I need to do is:

document.getElementById('id').style.width = value; 

It will change the inline stylesheet values. Normally this isn't a problem, because the inline style overrides the stylesheet. Example:

<style>    #tId {       width: 50%;    } </style>  <div id="tId"></div> 

Using this Javascript:

document.getElementById('tId').style.width = "30%"; 

I get the following:

<style>    #tId {       width: 50%;    } </style>  <div id="tId" style="width: 30%";></div> 

This is a problem, because not only do I not want to change inline values, If I look for the width before I set it, when I have:

<div id="tId"></div> 

The value returned is Null, so if I have Javascript that needs to know the width of something to do some logic (I increase the width by 1%, not to a specific value), getting back Null when I expect the string "50%" doesn't really work.

So my question: I have values in a CSS style that are not located inline, how can I get these values? How can I modify the style instead of the inline values, given an id?

like image 302
Coltin Avatar asked Feb 19 '09 16:02

Coltin


People also ask

Can we change CSS properties values using JavaScript?

CSS variables have access to the DOM, which means that you can change them with JavaScript.

How do you change a value in CSS?

No, CSS cannot change the value attribute of an input , or indeed any attribute of any element.

How do you target a CSS variable in JavaScript?

Setting a CSS Variable's Value To set the value of a CSS variable using JavaScript, you use setProperty on documentElement 's style property: document. documentElement. style .

Can we change CSS property value using JavaScript or jQuery?

You can change CSS using the jQuery css() method which is used for the purpose of getting or setting style properties of an element. Using this method you can apply multiple styles to an HTML all at once by manipulating CSS style properties.


2 Answers

Ok, it sounds like you want to change the global CSS so which will effictively change all elements of a peticular style at once. I've recently learned how to do this myself from a Shawn Olson tutorial. You can directly reference his code here.

Here is the summary:

You can retrieve the stylesheets via document.styleSheets. This will actually return an array of all the stylesheets in your page, but you can tell which one you are on via the document.styleSheets[styleIndex].href property. Once you have found the stylesheet you want to edit, you need to get the array of rules. This is called "rules" in IE and "cssRules" in most other browsers. The way to tell what CSSRule you are on is by the selectorText property. The working code looks something like this:

var cssRuleCode = document.all ? 'rules' : 'cssRules'; //account for IE and FF var rule = document.styleSheets[styleIndex][cssRuleCode][ruleIndex]; var selector = rule.selectorText;  //maybe '#tId' var value = rule.value;            //both selectorText and value are settable. 

Let me know how this works for ya, and please comment if you see any errors.

like image 114
Mike Avatar answered Oct 14 '22 14:10

Mike


Please! Just ask w3 (http://www.quirksmode.org/dom/w3c_css.html)! Or actually, it took me five hours... but here it is!

function css(selector, property, value) {     for (var i=0; i<document.styleSheets.length;i++) {//Loop through all styles         //Try add rule         try { document.styleSheets[i].insertRule(selector+ ' {'+property+':'+value+'}', document.styleSheets[i].cssRules.length);         } catch(err) {try { document.styleSheets[i].addRule(selector, property+':'+value);} catch(err) {}}//IE     } } 

The function is really easy to use.. example:

<div id="box" class="boxes" onclick="css('#box', 'color', 'red')">Click Me!</div> Or: <div class="boxes" onmouseover="css('.boxes', 'color', 'green')">Mouseover Me!</div> Or: <div class="boxes" onclick="css('body', 'border', '1px solid #3cc')">Click Me!</div> 

Oh..


EDIT: as @user21820 described in its answer, it might be a bit unnecessary to change all stylesheets on the page. The following script works with IE5.5 as well as latest Google Chrome, and adds only the above described css() function.
(function (scope) {     // Create a new stylesheet in the bottom     // of <head>, where the css rules will go     var style = document.createElement('style');     document.head.appendChild(style);     var stylesheet = style.sheet;     scope.css = function (selector, property, value) {         // Append the rule (Major browsers)         try { stylesheet.insertRule(selector+' {'+property+':'+value+'}', stylesheet.cssRules.length);         } catch(err) {try { stylesheet.addRule(selector, property+':'+value); // (pre IE9)         } catch(err) {console.log("Couldn't add style");}} // (alien browsers)     } })(window); 
like image 31
Leonard Pauli Avatar answered Oct 14 '22 14:10

Leonard Pauli