n1c9
n1c9

Reputation: 2687

Is there any way to make an SVG object clickable?

I'm working with the SVG that can be viewed here: http://n1t2.info/

I would just post the SVG, but because of the street maps layer the file is extremely large. However, you can see if you click the link that it's a map divided into 18 different svg paths, with a number of different colors shading them. My goal with this map is to make each of the 18 different sections clickable, or be able to give them an <a href="example.com">. Is this possible with SVGs at all?

edit: A comment suggested a show the way that I'm constructing the SVG file. You can see my method for that here.

Upvotes: 1

Views: 2357

Answers (3)

Kaiido
Kaiido

Reputation: 136638

IMO, the best solution is the SVG <a> element.

<svg width="200" height="200" viewBox="0 0 400 400" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

  <a xlink:href="http://stackoverflow.com/questions/15532371/do-svg-docs-support-custom-data-attributes">

    <path d="M 100 100 L 300 100 L 200 300 z" fill="orange" stroke="black" stroke-width="3"></path>

  </a>

</svg>

Upvotes: 2

Frondor
Frondor

Reputation: 3466

You can handle it pretty easily by adding a data attribute to each <path> element and then handle it via jquery or just javascript.

  1. First, add something like data-url="http://your-url.com" to the <path> element. Example: <path data-url="http://your-url.com">.

  2. Add jquery library just before the closing of your </body> tag, and the script in step #3 just like:

                    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
                    <script>
                            //your script
                    </script>
            </body>
    </html>
    
  3. instead of //your script you'll paste this one:

    $(document).ready(function(){
            $('path').on('click', function(e){
                e.preventDefault();
                var url = $(this).data('url');
                console.log('Moving to:', url);
                window.open(url, '_blank');
            });
    });
    
  4. Test it: http://jsfiddle.net/jpvu852d/

Upvotes: 2

PeterTheLobster
PeterTheLobster

Reputation: 1395

A search on google turned up this jQuery plugin for decorating image maps that may help you achieve your goal:

http://www.outsharked.com/imagemapster/default.aspx?what.html

Upvotes: 0

Related Questions