kaddindar
kaddindar

Reputation: 23

Controlling SVG Rectangle height and width with variables in JS

I need to create rectangles based on variable height and width in JavaScript. Here is the original code https://www.w3schools.com/graphics/tryit.asp?filename=trysvg_rect

that I I have tried to modify for variable height but it is not working

<!DOCTYPE html>
<html>
<body>
<script>
var h=50
<svg width="400" height="110">
  <rect width="300" height=`${h}` style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
  Sorry, your browser does not support inline SVG.  
</svg>
 </script>
</body>
</html>

I have tried other variations like + h + and ${h} but none are working and rectangle does not show up

Upvotes: 1

Views: 755

Answers (1)

bas
bas

Reputation: 15462

That syntax is invalid.

There are multiple ways to go about doing this.

You could dynamically set the innerHTML of the body using template literals:

<!DOCTYPE html>
<html>
<body>
  <script>
    var h = 50;

    document.body.innerHTML += `
      <svg width="400" height="110">
        <rect width="300" height=${h} style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
        Sorry, your browser does not support inline SVG.  
      </svg>
    `;
  </script>
</body>
</html>

Or you could give the rect element an id and use setAttribute to set the height attribute of the rect:

<!DOCTYPE html>
<html>
<body>
  <svg width="400" height="110">
  <rect id="rect" width="300" height="300" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
  Sorry, your browser does not support inline SVG.  
  </svg>
  <script>
    document.getElementById("rect").setAttribute("height", 50);
  </script>
</body>
</html>

There are also a lot of templating engines that allow you to do this in a more declarative way, but these are too many to mention all here so you can google that if you're interested.

Update

Triggering change of attribute based on event:

<!DOCTYPE html>
    <html>
    <body>
      <svg width="400" height="110">
      <rect id="rect" width="300" height="300" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
      Sorry, your browser does not support inline SVG.  
      </svg>
      <script>
        const rect = document.getElementById("rect");
        rect.onmouseover = function () {
            rect.setAttribute("height", 50);
        };
      </script>
    </body>
    </html>

Upvotes: 1

Related Questions