Search code examples
htmlcsssvganchorhref

Linking an SVG polygon to an anchor


I'm trying to do something seemingly relatively simple, but after much googling and finicking , I can't seem to make it work. I have an svg polygon that I'm using to clip an image into a triangle. Currently it's inside a bootstrap column, (with an a tag in it) that links to an anchor point. The issue with this, is that the div(square) all links to the anchor.

However, I have a bunch of these triangles adjoining, so I need the area that links to the anchor to be restricted to only what's inside the polygon clip path.

I have tried:

  • Moving the a tag inside the clippath tag
  • moving the a tag inside the polygon (as an href)
  • making the href in this format for svg xlink:href="#portfolioModal3"

I suspect it's some permutation of the third option that accomplishes my goal.

<div class="col-sm-4 portfolio-item dontwantpadding">
                    <a href="#portfolioModal3" class="portfolio-link" data-toggle="modal">
                        <div class='tri-up'>
                            <svg width="100%" height="100%" viewBox="0 0 100 87">
                              <clipPath id="clipTriangleUp">
                                <polygon points="0 87,100 87,50 0"/>
                              </clipPath>
                              <image clip-path="url(#clipTriangleUp)" preserveAspectRatio="none" width="100%" height="100%" xlink:href="http://placehold.it/1749x1510"/>
                            </svg>
                        </div>
                    </a>
                </div>

I plan on making the svg paths transition to circles from triangles, so something that will adapt to a circle svg path is ideal.

Any help is much appreciated!


Solution

  • SVGs can have <a> elements. Try putting your link inside your SVG.

    <div class="col-sm-4 portfolio-item dontwantpadding">
       <div class='tri-up'>
          <svg width="100%" height="100%" viewBox="0 0 100 87">
             <clipPath id="clipTriangleUp">
                <polygon points="0 87,100 87,50 0"/>
             </clipPath>
             <a id="svgtriangle"
                xlink:href="#portfolioModal3" class="portfolio-link" data-toggle="modal">
                <image clip-path="url(#clipTriangleUp)" preserveAspectRatio="none"
                       width="100%" height="100%"
                       xlink:href="http://placehold.it/1749x1510"/>
             </a>
          </svg>
       </div>
    </div>
    

    Hopefully you won't have any issue with Bootstrap finding the data-toggle.

    Update

    Okay, so it seems Bootstrap won't find your modal "open" link automatically, so you need to add a click handler to the triangle and open the modal yourself.

    var  triangle = document.getElementById("svgtriangle");
    
    triangle.addEventListener('click', function(evt) {
        $('#myModal').modal('show');
    });
    

    Demo fiddle here