PDA

View Full Version : currentStyle doesn't take value from CSS



Madis
Mar 18th, 2007, 02:21 PM
I made a "toggle anything in anyway" JS, function code is:


function changestyle(id,eljs,newvalue) {
var thething = document.getElementById(id);

if (thething.style[eljs]==newvalue) {
// if new value is already added

if (window.getComputedStyle) {
thething.style[eljs] = document.defaultView.getComputedStyle(thething,'').getPropertyValue(eljs);
} else {
// For Internet Explorer
thething.style[eljs] = thething.currentStyle[eljs];
}

} else {
// if new value is not added already
thething.style[eljs] = newvalue;
}

}

And function using example:

The style:

.mainlr {
margin-left: 170px;
margin-right: 170px;
}


The HTML:

<img src="images/toggle.jpg" onclick="changestyle('main','marginRight','0px');" />
<br /><div class="mainlr" id="main">This will have margin</div>


It works in Opera and Firefox, but if using Internet Explorer, it won't toggle back if clicking twice.
The problem is in this:

thething.style[eljs] = thething.currentStyle[eljs];
thething.currentStyle[eljs]; should show what "marginRight" ("margin-right" also doesn't work) does element "main" have for it.

But it takes the value of thething.style[eljs], which was given with first click.
Opera and FF take it from class "mainlr", like I want to.

(If putting in CSS

#main {
margin-left: 170px;
margin-right: 170px;
}
it still won't work with IE...)

Can anyone help me?

Sorry, if text was too messy.

jkd
Mar 18th, 2007, 08:36 PM
Try setting the runtimeStyle instead of the currentStyle.

Madis
Mar 19th, 2007, 01:49 AM
:thumbsup:
Thankyou! It worked perfectly.
You're the greatest!