how to set the radius of a shape to bigger or smaller by pressing buttons in javascript/svg

dom, javascript, svg

Solution

As noted by pp19dd, in his answer, the key is `setAttribute()`, but as it seems you want to increase/decrease the `r` attribute of the `circle` elements (and not simply set it to a particular value), you'll need to use `getAttribute()` as well.

This is a fairly simple function and implementation that, I think, does what you wanted:

function circle(delta){
    if (!delta){
        return false;
    }
    else {
        var e = document.querySelectorAll('circle[id^=circle]'),
            changeBy = 10;
        if (delta == 'big'){
            e[0].setAttribute('r',parseInt(e[0].getAttribute('r'),10) + changeBy);
            e[1].setAttribute('r',parseInt(e[1].getAttribute('r'),10) + changeBy);
        }
        else if (delta == 'small'){
            e[0].setAttribute('r',parseInt(e[0].getAttribute('r'),10) - changeBy);
            e[1].setAttribute('r',parseInt(e[1].getAttribute('r'),10) - changeBy);
        }
    }
}

var inputs = document.getElementsByTagName('input'),
    buttons = [];

for (var i = 0, len = inputs.length; i < len; i++) {
    if (inputs[i].type == 'button') {
        inputs[i].onclick = function(){
            circle(this.value);
        }
    }
}

​​JS Fiddle demo.

Note that I've not implemented any checks for invalid negative values for the circle's `r` attribute. You may want to add that yourself.

And I used `document.querySelectorAll()` for simplicity (rather than two explicit calls to `document.getElementById()`). This will cause problems in Internet Explorer, though I'm unsure as to how well implemented SVG is in Internet Explorer, so it might not make things any worse.

Having said all that, though, it seems that IE 9 implements the demo perfectly. Which surprises me no end..! IE 8, and lower, though, I'm unable to say.

References:

- `document.querySelectorAll()`.

- `element.getAttribute()`.

- `element.setAttribute()`.

- `parseInt()`.

Problem

Hi I have the following code and I want to be able to change the radius of a circle by pressing a button I dont know what to use after style. in the document.getElementById("circle1").style.r="10"; part of the code ``` <html> <head> <script> function circle() { document.getElementById("circle").style.r="50"; } function circle1() { document.getElementById("circle1").style.r="10"; } </script> </head> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="svg" > <circle id = "circle" cx = "100" cy = "800" r = "30" stroke="blue" stroke-width = "2" fill = "black"/> <circle id = "circle1" cx = "20" cy = "500" r = "30" stroke="blue" stroke-width = "2" fill = "black"/> </svg> <body> Set size of circles <input type="button" onclick="circle()" value="big" /> <input type="button" onclick="circle1()" value="small" /> </body> </html> ```

Original source