momo
momo

Reputation: 31

Changing viewBox of an svg in javaScript

I am trying to change my viewBox using JS without any success

var mySVG = document.getElementById('svg');
if ($(window).width() >960) {
   mySVG.setAttribute("viewBox", "400 400 400 400"); 
}

Upvotes: 2

Views: 1400

Answers (2)

Dominik
Dominik

Reputation: 6313

Your code works just fine when it comes to changing the attribute provided you use an ID in the SVG:

function setViewBox() {
  var mySVG = document.getElementById('svg');
  //if ($(window).width() >960) { // <-- disabled so we can test it here
     mySVG.setAttribute("viewBox", "400 400 400 400"); 
  //}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<svg id="svg" viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg" width="100px" height="100px">
  <rect x="0" y="0" width="100%" height="100%" fill="#000"/>
</svg>

<button onClick="setViewBox()">set viewBox</button>

I decreased the screen size boundary that you set for you to test it here:

function setViewBox() {
  var mySVG = document.getElementById('svg');
  if ($(window).width()>100) { // <-- reduced the size so you can test it
     mySVG.setAttribute("viewBox", "400 400 400 400"); 
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<svg id="svg" viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg" width="100px" height="100px">
  <rect x="0" y="0" width="100%" height="100%" fill="#000"/>
</svg>

<button onClick="setViewBox()">set viewBox</button>

Upvotes: 2

Robert
Robert

Reputation: 2763

Set attribute works:) so probably don't work conditional statement

var mySVG = document.getElementById('svg');

mySVG.setAttribute("viewBox", "0 0 200 200"); 

function changeViewBox(viewBox){ 
  mySVG.setAttribute("viewBox", viewBox); 
}
<button onclick='changeViewBox("0 0 300 300")'>0 0 300 300</button>
<button onclick='changeViewBox("0 0 400 400")'>0 0 400 400</button>
<button onclick='changeViewBox("0 0 500 500")'>0 0 500 500</button>

<svg id="svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 120"><style>.st0{fill:#bcbbbb}.st1{fill:#f48023}</style><path class="st0" d="M84.4 93.8V70.6h7.7v30.9H22.6V70.6h7.7v23.2z"/><path class="st1" d="M38.8 68.4l37.8 7.9 1.6-7.6-37.8-7.9-1.6 7.6zm5-18l35 16.3 3.2-7-35-16.4-3.2 7.1zm9.7-17.2l29.7 24.7 4.9-5.9-29.7-24.7-4.9 5.9zm19.2-18.3l-6.2 4.6 23 31 6.2-4.6-23-31zM38 86h38.6v-7.7H38V86z"/></svg>

Upvotes: 2

Related Questions