Vikas Kandari
Vikas Kandari

Reputation: 1851

How to get a parameter form a javascript function as text

<div id="demo" onclick="applycss(250,500,"red")"></div>
<script>
    function applycss(){
        var box = document.getElementById("this.id").style;
        box.height = fisrt parameter;
        box.width = second parameter;
        box.backgroundColor = third parameter;
    }
</script>

How to do this? I want to apply value 250, 500, red to div on click so that I can use this function to any element without long coding.

Upvotes: 0

Views: 68

Answers (2)

Parkash Kumar
Parkash Kumar

Reputation: 4730

You have some syntax error, see updated code. For multiple CSS properties, you need to create css-string of your parameter values and set it as following:

HTML:

<div id="demo" onclick="applycss(this, '250', '500', 'red');">Div to apply CSS</div>

JS:

function applycss(obj, height, width, bgColor){
    var cssStyle = "height: " + height + "px; ";
    cssStyle += "width: " + width + "px; ";
    cssStyle += "background-color: " + bgColor + ";";

    if(typeof(obj.style.cssText) != 'undefined')
        obj.style.cssText = cssStyle;
    else
        obj.setAttribute('style', cssStyle);
}

DEMO

Upvotes: 1

danleyb2
danleyb2

Reputation: 1068

try this

<script>
     function applycss(fisrt,second,third){
        var box = document.getElementById("demo").style;
          box.height=fisrt;
          box.width=  second;
          box.backgroundColor= third;
}
 </script>

Upvotes: 2

Related Questions