How to change CSS Class style by JS - javascript

I have a css clas like this:
.title-bottom:before {
bottom: -5px;
content: "";
height: 2px;
left: 0;
position: absolute;
width: 80px;
}
left:0 sets the underscore to left but when RTL active, it must be float right.So, I want to change left:0 to left:initial if rtl exist.
How can I do it? I started to write the code like this:
if (document.dir === 'rtl'){
but I couldnt continue it.Because I couldnt find good resources to learn JS.
I need a code for this problem, Also good resources to learn JS.

You are seeking to change a CSS rule for the entire document.
One way to do this is to append a style sheet to your document's <head>, and put the rule changes in there. Since the added style sheet is the last one in the document, it will override the default rule.
if (document.dir === 'rtl') {
// create a new style sheet and append to head
let newStyle = document.createElement('style');
newStyle.innerHTML = '.title-bottom:before { left:initial; }';
document.head.appendChild(newStyle);
}
function addRtl() {
let newStyle = document.createElement('style');
newStyle.innerHTML = '.title-bottom:before { content: ".rtl"; }';
document.head.appendChild(newStyle);
document.dir = 'rtl';
}
.title-bottom {
background-color: lightgray;
padding: 1rem;
}
<body>
<h1>RTL Style Manipulation</h1>
<button onclick="addRtl()">Add New Style Sheet</button>
<div class="title-bottom">.title-bottom</div>
</body>
Alternative Method: CSS Attributes
But since you are basing the changes on an attribute called 'dir', you don't need any JavaScript to accomplish this. Instead, you can make use of the CSS [attribute=value] selector.
The CSS attribute selector has the form [attribute=value], which will match an element that has that attribute set to that value.
To make style modification when document.dir === 'rtl', you would use:
[dir*=rtl] .title-bottom:before {
left:initial;
}
A little example showing how to use CSS attribute selector:
function rtl() {
document.dir = 'rtl';
}
function ltr() {
document.dir = 'ltr';
}
[dir=rtl] p {
color: red;
}
<h1>Change document.dir</h1>
<button onclick="rtl()">set rtl</button>
<button onclick="ltr()">set ltr</button>
<p>Paragraph text will be red when document.dir === 'rtl'</p>

Related

Deleting <style> elements when adding new ones with JS

I'm trying to make a page that has 3 buttons that make the background change color. I know how to do this, theoretically. I've been trying to build the methods for changing the background color but whenever I change the color, it's because the new style element overlaps the old one(s), so I'm looking for a way to delete the previous one when the new one is created but I've yet to find it.
var backgroundColor = {
red: function backgroundRed() {
var sheet = document.createElement('style');
sheet.setAttribute('id', 'redBG');
sheet.innerHTML = "body {background-color: red;}";
document.body.appendChild(sheet);
},
blue: function backgroundBlue() {
var sheet = document.createElement('style');
sheet.setAttribute('id', 'blueBG');
sheet.innerHTML = "body {background-color: blue;}";
document.body.appendChild(sheet);
},
green: function backgroundGreen() {
var sheet = document.createElement('style');
sheet.setAttribute('id', 'greenBG');
sheet.innerHTML = "body {background-color: limegreen;}";
document.body.appendChild(sheet);
},
deletePrevious: function() {
// ???
},
};
var applyColor = {
applyRed: function() {
//a method that when applying a new background color deletes the previous one
backgroundColor.red();
},
applyBlue: function() {
backgroundColor.blue();
},
applyGreen: function() {
backgroundColor.green();
}
}
This is the code I've written so far. The thing is, when I run it, this is what happens: Overlapping elements
How can I make a method that deletes the previous elements? Should I nest the elements within a div?
Edit: Turns out I'm wildly overthinking this. I'm been learning JS for about 2 months now, still have a long way to go. Andrew Lohr's comment effectively replaces all the backgroundColor functions I created. I'm also new to StackOverflow so I haven't found a way to upvote his comment yet. I need to get more acquainted with the DOM and easier ways to modify it.
Thank you all for your responses and your help.
You look like you're familiar with JS, so tell me if you need a example.
Make a style tag with the 'themeCSS'. Then, every time you want to add/replace the CSS, use:
themeCSS.innerHTML = "so { and: so; }";
That way, it'll always replace the previous CSS :)
Instead of changing the entire CSS <style> tag just set a value in the class` attribute that sets the overall theme and all of your CSS is based on that theme.
body.theme-red {
background-color: red;
}
body.theme-blue {
background-color: blue;
}
body.theme-green {
background-color: green;
}
.theme-red h1 {
color: black
}
.theme-blue h1 {
color: yellow;
}
.theme-green h1 {
color: red;
}
Or, break your CSS into three files and only load the correct one based on the theme.
Or, break you CSS into three files and use Alternate Style Sheets.

is there a simple way to replace a style by another in fullcalendar

i would like to change all the occurrence style="width: 1px;" by style="width: 41px;" in fullcalendar agendaWeek after it render,
for that i used eventAfterRender
and my code is
eventAfterRender: function(event, $el, view) {
if( 'agendaWeek' === view.name ) {
var r = new RegExp(style="width: 1px;", "g");
var txtWith = 'style="width: 41px;"';
$el.find(".fc-body").val().replace(r,
txtWith).
replace(/\</g, "<").replace(/\>/g,
">").replace(/\&/g, "&");
}
Instead of trying to change the inline style attribute, I would assign a CSS class which overrides the inline styling.
$el.addClass('wideCell');
The class .wideCell would be something like this:
.wideCell {
width: 41px !important;
}
If you absolutely want to go with the replacement strategy, I would advise to use the following regex:
function replaceInlineWidth(element) {
// When the element has no style attribute, skip it.
if (!element.hasAttribute('style')) {
return;
}
// Get the style attribute from the element
var inlineStyle = element.getAttribute('style'),
regex = /width\s?:\s?\d+px(?:;|$)/g;
// Replace the inline width declaration with 41px
inlineStyle = inlineStyle.replace(regex, 'width: 41px;');
// Set the modified style attribute back on the element.
element.setAttribute('style', inlineStyle);
}
// Create a test element.
var
element = document.createElement('div');
// Give the test element some inline style.
element.setAttribute('style', 'background-color: #000; width: 1px; margin: 1em;');
// Run the replacement method.
replaceInlineWidth(element);
// Log the inline style, the width should be 41px.
console.log(element.getAttribute('style'));
It will match things like width:1px, width :1px, and width: 1px. It also matches width: 30px. It will be a bit more resilient. If you really only want to replace width: 1px change the regex to width\s?:\s?1px(?:;|$).
to change fc-axis style,
First solution,
#Thijs idea
add to your css file,
.wideCell {
width: 41px !important;
}
go to fullcalendar.js and add wideCell to any class that contain fc-axis, EXP
'<td class="fc-axis fc-time '
become
'<td class="fc-axis fc-time wideCell '
without it i would have
fullcalendar weekview not showing correctly
but it should be like this fullcalendar weekview showing correctly
Second solution
open fullcalendar.js and change
var maxInnerWidth = 0; to var maxInnerWidth = 40;\\40 or what ever feet your need,

Is it possible to change css class properities through javascript? [duplicate]

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?
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.
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);
Gathering the code in the answers, I wrote this function that seems running well on my FF 25.
function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
/* returns the value of the element style of the rule in the stylesheet
* If no value is given, reads the value
* If value is given, the value is changed and returned
* If '' (empty string) is given, erases the value.
* The browser will apply the default one
*
* string stylesheet: part of the .css name to be recognized, e.g. 'default'
* string selectorText: css selector, e.g. '#myId', '.myClass', 'thead td'
* string style: camelCase element style, e.g. 'fontSize'
* string value optionnal : the new value
*/
var CCSstyle = undefined, rules;
for(var m in document.styleSheets){
if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
for(var n in rules){
if(rules[n].selectorText == selectorText){
CCSstyle = rules[n].style;
break;
}
}
break;
}
}
if(value == undefined)
return CCSstyle[style]
else
return CCSstyle[style] = value
}
This is a way to put values in the css that will be used in JS even if not understood by the browser. e.g. maxHeight for a tbody in a scrolled table.
Call :
CCSStylesheetRuleStyle('default', "#mydiv", "height");
CCSStylesheetRuleStyle('default', "#mydiv", "color", "#EEE");
I don't know why the other solutions go through the whole list of stylesheets for the document. Doing so creates a new entry in each stylesheet, which is inefficient. Instead, we can simply append a new stylesheet and simply add our desired CSS rules there.
style=document.createElement('style');
document.head.appendChild(style);
stylesheet=style.sheet;
function css(selector,property,value)
{
try{ stylesheet.insertRule(selector+' {'+property+':'+value+'}',stylesheet.cssRules.length); }
catch(err){}
}
Note that we can override even inline styles set directly on elements by adding " !important" to the value of the property, unless there already exist more specific "!important" style declarations for that property.
I don't have rep enough to comment so I'll format an answer, yet it is only a demonstration of the issue in question.
It seems, when element styles are defined in stylesheets they are not visible to getElementById("someElement").style
This code illustrates the issue... Code from below on jsFiddle.
In Test 2, on the first call, the items left value is undefined, and so, what should be a simple toggle gets messed up. For my use I will define my important style values inline, but it does seem to partially defeat the purpose of the stylesheet.
Here's the page code...
<html>
<head>
<style type="text/css">
#test2a{
position: absolute;
left: 0px;
width: 50px;
height: 50px;
background-color: green;
border: 4px solid black;
}
#test2b{
position: absolute;
left: 55px;
width: 50px;
height: 50px;
background-color: yellow;
margin: 4px;
}
</style>
</head>
<body>
<!-- test1 -->
Swap left positions function with styles defined inline.
Test 1<br>
<div class="container">
<div id="test1a" style="position: absolute;left: 0px;width: 50px; height: 50px;background-color: green;border: 4px solid black;"></div>
<div id="test1b" style="position: absolute;left: 55px;width: 50px; height: 50px;background-color: yellow;margin: 4px;"></div>
</div>
<script type="text/javascript">
function test1(){
var a = document.getElementById("test1a");
var b = document.getElementById("test1b");
alert(a.style.left + " - " + b.style.left);
a.style.left = (a.style.left == "0px")? "55px" : "0px";
b.style.left = (b.style.left == "0px")? "55px" : "0px";
}
</script>
<!-- end test 1 -->
<!-- test2 -->
<div id="moveDownThePage" style="position: relative;top: 70px;">
Identical function with styles defined in stylesheet.
Test 2<br>
<div class="container">
<div id="test2a"></div>
<div id="test2b"></div>
</div>
</div>
<script type="text/javascript">
function test2(){
var a = document.getElementById("test2a");
var b = document.getElementById("test2b");
alert(a.style.left + " - " + b.style.left);
a.style.left = (a.style.left == "0px")? "55px" : "0px";
b.style.left = (b.style.left == "0px")? "55px" : "0px";
}
</script>
<!-- end test 2 -->
</body>
</html>
I hope this helps to illuminate the issue.
Skip
You can get the "computed" styles of any element.
IE uses something called "currentStyle", Firefox (and I assume other "standard compliant" browsers) uses "defaultView.getComputedStyle".
You'll need to write a cross browser function to do this, or use a good Javascript framework like prototype or jQuery (search for "getStyle" in the prototype javascript file, and "curCss" in the jquery javascript file).
That said if you need the height or width you should probably use element.offsetHeight and element.offsetWidth.
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)
Mind, if you add an inline style to the element in question, it can act as the "default" value and will be readable by Javascript on page load, since it is the element's inline style property:
<div style="width:50%">....</div>
This simple 32 lines gist lets you identify a given stylesheet and change its styles very easily:
var styleSheet = StyleChanger("my_custom_identifier");
styleSheet.change("darkolivegreen", "blue");
I've never seen any practical use of this, but you should probably consider DOM stylesheets. However, I honestly think that's overkill.
If you simply want to get the width and height of an element, irrespective of where the dimensions are being applied from, just use element.offsetWidth and element.offsetHeight.
Perhaps try this:
function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
var CCSstyle = undefined, rules;
for(var m in document.styleSheets){
if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
for(var n in rules){
if(rules[n].selectorText == selectorText){
CCSstyle = rules[n].style;
break;
}
}
break;
}
}
if(value == undefined)
return CCSstyle[style]
else
return CCSstyle[style] = value
}

How to dynamically create a css style rule that is overridable by earlier rules

I have been using jss in my project to do dynamic styles. This has worked great for the most part, but I want to do something it seems to not help with.
I want to be able to create a set of main style rules first, then create a set of default style rules that can be overridden by the main style rules if they conflict. Example:
<div class="mainClass1 defaultClass1">text</div>
<script>
jss.set('.mainClass1', {
color: 'red'
})
jss.set('.defaultClass1', {
color: 'green'
})
</script>
I want the outcome to be that the text is red, but the way jss operates, the text comes out green. I was hoping I could somehow create two dynamic stylesheets, the "default" sheet being first, and the "main" sheet being second (so that main overrides default). Is this possible?
Update - I confirmed a technique that works with raw javascript:
var styleNode = document.createElement('style');
styleNode.type = 'text/css';
styleNode.rel = 'stylesheet';
document.head.appendChild(styleNode);
//styleNode.sheet.insertRule("#A" + ' { color:green; }', 1);
var styleNode2 = document.createElement('style');
styleNode2.type = 'text/css';
styleNode2.rel = 'stylesheet';
document.head.appendChild(styleNode2);
styleNode2.sheet.insertRule("#A" + ' { color:green; }', 0);
styleNode.sheet.insertRule("#A" + ' { color:red; }', 0);
The element with id 'A' remains green even after the red style is added on the earlier stylesheet. Now I'm just wondering if I can do this with jss or if I need to roll something of my own.
Why does this not work?
var jss1 = jss.forDocument(document)
var jss2 = jss.forDocument(document)
jss2.set('#A', {
color: 'green'
})
jss1.set('#A', {
color: 'red'
})
A brief inspection of the jss source leads me to believe that your answer lies in creating different stylesheets. From my brief perusal it seems that CSS in stylesheets created later override CSS in previously created stylesheets.
"Read the source"
Using CSS selectors
You can do this very simply, just use the multiple classes selector:
jss.set('.defaultClass1.mainClass1', {...});
This has a higher class specificity than the .defaultClass selector.
Using the JSS-extend plugin
This JSS plugin simplifies extending styles. For example you can do this (copied from an example in the repository.
var button0 = {
padding: '20px',
background: 'blue'
}
var redButton = {
background: 'red'
}
window.styles = {
button0: button0,
button1: {
extend: [button0, redButton],
'font-size': '20px'
}
}
This registers the button0and button1 styles to the current window (just like linking a CSS file).
Allllright, I figured out how to do it with jss:
<div id="a">A div</div>
<script>
var jss1 = jss.forDocument(document)
jss1.defaultSheet = jss1._createSheet()
var jss2 = jss.forDocument(document)
jss2.defaultSheet = jss2._createSheet()
jss2.set('#A', {
color: 'green'
})
jss1.set('#A', {
color: 'red'
})
</script>
I found out jss lazily creates its sheet. So if you want to ensure the order of the stylesheets, you need to create them up front with _createSheet.

Change css of static class with javascript [duplicate]

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?
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.
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);
Gathering the code in the answers, I wrote this function that seems running well on my FF 25.
function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
/* returns the value of the element style of the rule in the stylesheet
* If no value is given, reads the value
* If value is given, the value is changed and returned
* If '' (empty string) is given, erases the value.
* The browser will apply the default one
*
* string stylesheet: part of the .css name to be recognized, e.g. 'default'
* string selectorText: css selector, e.g. '#myId', '.myClass', 'thead td'
* string style: camelCase element style, e.g. 'fontSize'
* string value optionnal : the new value
*/
var CCSstyle = undefined, rules;
for(var m in document.styleSheets){
if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
for(var n in rules){
if(rules[n].selectorText == selectorText){
CCSstyle = rules[n].style;
break;
}
}
break;
}
}
if(value == undefined)
return CCSstyle[style]
else
return CCSstyle[style] = value
}
This is a way to put values in the css that will be used in JS even if not understood by the browser. e.g. maxHeight for a tbody in a scrolled table.
Call :
CCSStylesheetRuleStyle('default', "#mydiv", "height");
CCSStylesheetRuleStyle('default', "#mydiv", "color", "#EEE");
I don't know why the other solutions go through the whole list of stylesheets for the document. Doing so creates a new entry in each stylesheet, which is inefficient. Instead, we can simply append a new stylesheet and simply add our desired CSS rules there.
style=document.createElement('style');
document.head.appendChild(style);
stylesheet=style.sheet;
function css(selector,property,value)
{
try{ stylesheet.insertRule(selector+' {'+property+':'+value+'}',stylesheet.cssRules.length); }
catch(err){}
}
Note that we can override even inline styles set directly on elements by adding " !important" to the value of the property, unless there already exist more specific "!important" style declarations for that property.
I don't have rep enough to comment so I'll format an answer, yet it is only a demonstration of the issue in question.
It seems, when element styles are defined in stylesheets they are not visible to getElementById("someElement").style
This code illustrates the issue... Code from below on jsFiddle.
In Test 2, on the first call, the items left value is undefined, and so, what should be a simple toggle gets messed up. For my use I will define my important style values inline, but it does seem to partially defeat the purpose of the stylesheet.
Here's the page code...
<html>
<head>
<style type="text/css">
#test2a{
position: absolute;
left: 0px;
width: 50px;
height: 50px;
background-color: green;
border: 4px solid black;
}
#test2b{
position: absolute;
left: 55px;
width: 50px;
height: 50px;
background-color: yellow;
margin: 4px;
}
</style>
</head>
<body>
<!-- test1 -->
Swap left positions function with styles defined inline.
Test 1<br>
<div class="container">
<div id="test1a" style="position: absolute;left: 0px;width: 50px; height: 50px;background-color: green;border: 4px solid black;"></div>
<div id="test1b" style="position: absolute;left: 55px;width: 50px; height: 50px;background-color: yellow;margin: 4px;"></div>
</div>
<script type="text/javascript">
function test1(){
var a = document.getElementById("test1a");
var b = document.getElementById("test1b");
alert(a.style.left + " - " + b.style.left);
a.style.left = (a.style.left == "0px")? "55px" : "0px";
b.style.left = (b.style.left == "0px")? "55px" : "0px";
}
</script>
<!-- end test 1 -->
<!-- test2 -->
<div id="moveDownThePage" style="position: relative;top: 70px;">
Identical function with styles defined in stylesheet.
Test 2<br>
<div class="container">
<div id="test2a"></div>
<div id="test2b"></div>
</div>
</div>
<script type="text/javascript">
function test2(){
var a = document.getElementById("test2a");
var b = document.getElementById("test2b");
alert(a.style.left + " - " + b.style.left);
a.style.left = (a.style.left == "0px")? "55px" : "0px";
b.style.left = (b.style.left == "0px")? "55px" : "0px";
}
</script>
<!-- end test 2 -->
</body>
</html>
I hope this helps to illuminate the issue.
Skip
You can get the "computed" styles of any element.
IE uses something called "currentStyle", Firefox (and I assume other "standard compliant" browsers) uses "defaultView.getComputedStyle".
You'll need to write a cross browser function to do this, or use a good Javascript framework like prototype or jQuery (search for "getStyle" in the prototype javascript file, and "curCss" in the jquery javascript file).
That said if you need the height or width you should probably use element.offsetHeight and element.offsetWidth.
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)
Mind, if you add an inline style to the element in question, it can act as the "default" value and will be readable by Javascript on page load, since it is the element's inline style property:
<div style="width:50%">....</div>
This simple 32 lines gist lets you identify a given stylesheet and change its styles very easily:
var styleSheet = StyleChanger("my_custom_identifier");
styleSheet.change("darkolivegreen", "blue");
I've never seen any practical use of this, but you should probably consider DOM stylesheets. However, I honestly think that's overkill.
If you simply want to get the width and height of an element, irrespective of where the dimensions are being applied from, just use element.offsetWidth and element.offsetHeight.
Perhaps try this:
function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
var CCSstyle = undefined, rules;
for(var m in document.styleSheets){
if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
for(var n in rules){
if(rules[n].selectorText == selectorText){
CCSstyle = rules[n].style;
break;
}
}
break;
}
}
if(value == undefined)
return CCSstyle[style]
else
return CCSstyle[style] = value
}

Categories

Resources