3
votes

I want to increase the stroke width of a svg image by 0.5 when the user clicks on a button. I have the click function already, but not sure how to get the function to work to increase the stroke width.

function pipeScaleFactorPlus(){
    $(".pipe").style("stroke-width", "+=0.5");

  drawMapPipes();    
}

.pipe is the svg class and the drawMapPipes(); is called to redraw the svg image.

2
Can you create a minimal reproducible example? I.e. something we can run, even if it's broken.Robert Longson
What else do you need, like the click function as well? It's hard for me to create an example on codepen.io or something bc I'm pulling the svg from a db to create pipelines on a map.lostInTheTetons
Your example does not need to replicate the db thing it only needs to have a pre-created object whose stroke width you're trying to adjust.Robert Longson
Also, jQuery has no style() function. Are you using some other plugin that adds that function?Paul LeBeau

2 Answers

4
votes

Assuming you are using normal jQuery only. Here is how you can adjust the stroke width.

Note that we have to do a little extra to modify some SVG properties because some have names that differ from the style property names.

For example, the attribute is named stroke-width, but the style property is strokeWidth.

$("button").click(function(evt) {
  var myLine = $("line");
  // Get the current stroke-width.
  // Try getting it from the style object first. Otherwise get it direct
  // from the attribute value.
  // We use parseInt() to strip off any units ("20px" -> 20)
  var currentWidth = parseInt(myLine.css("strokeWidth") || myLine.attr("stroke-width"), 10);
  // Update the style property "strokeWidth".
  // Note that the property has a different spelling to the attribute.
  myLine.css("strokeWidth", 30 - currentWidth);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<svg>
  <line y1="75" x2="300" y2="75" stroke="black" stroke-width="10"/>
</svg>

<button>Click me</button>
1
votes

I figured it out.. I was trying to make it more complicated then it had to be. I just created a new variables and set stroke widths to begin with and then added the function within the click function.

    $("#increasePipe").click(function(){
      map.pipeSize += 0.25;
        if (map.pipeSize > map.pipeSizeMax){
            map.pipeSize = map.pipeSizeMax;
        }
      map.svg.selectAll(".pipe").style("stroke-width", map.pipeSize);
    });