Search code examples
svgfancyboxanchorimagemapclickable

Clickable SVG paths to open fancybox


In short, I have a pie chart graphic that when a segment is clicked it should open a fancybox overlay. I tried using a map which worked fine but it wasn't 100% accurate, the edges weren't rounded and I can't apply any hover styles.

So I decided to create an SVG with the pie chart segments (paths) on top of the graphic. This means the SVG paths now match the shapes on the pie chart exactly. Here is the code for the SVG:

<figure class="align-center">
    <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 760 580" xml:space="preserve">
        <image xlink:href="../../img/content/diagrams/background-graphic.png" x="0" y="0" height="580px" width="760px" />
        <path class="st0" d="M251.9,456.4C287.4,483.7,331.8,500,380,500c11.8,0,23.3-1,34.6-2.8L380,290L251.9,456.4z" />
        <path class="st0" d="M380,80c-116,0-210,94-210,210c0,67.8,32.1,128,81.9,166.4L380,290V80z" />
        <path class="st0" d="M527.3,439.6C566,401.6,590,348.6,590,290c0-116-94-210-210-210v210L527.3,439.6z" />
        <path class="st0" d="M380,290l129.3,165.5c6.3-4.9,12.3-10.2,18-15.8L380,290z" />
        <path class="st0" d="M414.6,497.2c35.3-5.9,67.7-20.5,94.8-41.7L380,290L414.6,497.2z" />
    </svg>
</figure>

Now I need to somehow make the path element behave like an anchor. You could add an href to the area elements within a map but it doesn't seem like you can do that with an SVG?

There markup for the hidden content is simple and looks like this:

<div id="overlay-1" class="hide">
    <h3>Overlay title</h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>

The usual behaviour would be this opens once an object with the corresponding href value was clicked.

What's the best practice for this - if there is such a thing?


Solution

  • If you can attach click event to your element, then there is no reason why it could not be used to trigger fancyBox.

    Simply add data-src and data-fancybox attributes if using fancyBox v3.

    Example:

    <path data-fancybox data-src="https://farm4.staticflickr.com/3953/15594397982_477385f90d_b_d.jpg" class="st0" d="M251.9,456.4C287.4,483.7,331.8,500,380,500c11.8,0,23.3-1,34.6-2.8L380,290L251.9,456.4z" />

    Demo - https://codepen.io/anon/pen/vJreVd?editors=1000

    Another solution would be to create custom click event for your path elements and call fancyBox manually. Demo - http://jsfiddle.net/ymhvdeqy/1/