Forum Moderators: open

Message Too Old, No Replies

Dynamic CSS Property/Value Switcher

onevent change id's property to new value

         

JAB Creations

3:19 am on Sep 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



For contrast here is a dynamic ID/Width changer I've modded from a class changer...

JavaScript

// Width Change
function changewidth(id, newWidth)
{
identity=document.getElementById(id);
identity.style.width=newWidth;
}

(X)HTML

<element onclick="changewidth('content', '100%');"

It makes sense to also allow which CSS property would be choosen in addition to the value. So this is what we feed to the script...

1.) Element's ID
2.) The CSS property (could be width, border, etc).
3.) The value for the CSS property (100%, red, underline, etc).

What I'm not sure of is how to assign all this together. I don't have any good working examples of that. Here is what I have thus far...

JavaScript

// Dynamic CSSJS Change
function changecss(id, cssproperty, cssvalue)
{
identity=document.getElementById(id);
identity.style=cssproperty;
identity.style.value=cssvalue;
}

(X)HTML

<element onevent="changecss('contentID', 'CSSProperty', 'CSSValue');"

I think that should make sense but I know how I'm associating the dynamic style is wrong.

JAB Creations

4:35 am on Sep 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Apple's Web Developer website actually was useful for once. :D Could someone please explain the brackets though? [p] Thanks!

JavaScript

// setStyleById: given an element id, style property and
// value, apply the style.
// args:
// i - element id
// p - property
// v - value
//
function setStyleById(i, p, v) {
var n = document.getElementById(i);
n.style[p] = v;
}

(X)HTML

<element onevent="setStyleById('content', 'width', '100%');"

- John

vincevincevince

4:47 am on Sep 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The square bracket [?] works the same as style.? but allows you to pass in a variable. If you tried n.style.p you'd be setting a style named 'p' and not whatever the variable p contains.

Consider adding to your code the use of 'this' so that you don't need to set an id and use getElementById(). 'this' will automatically refer to whatever element fired the event.

function setStyle(p, v) {
this.style[p] = v;
}

Dabrowski

8:09 pm on Sep 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I've been using the name notation for ages in other things, a couple of examples....

document['nameofimage'].src = "thing.jpg";
document.form['nameofinput'].value = "notexthere";