Explain Codes LogoExplain Codes Logo

Make an html svg object also a clickable link

html
responsive-design
pointer-events
aria-label
Anton ShumikhinbyAnton Shumikhin·Dec 17, 2024
TLDR

Wrap your SVG with an anchor <a> tag to create a clickable link. Here's how to do that:

<a href="https://www.example.com"> <svg height="100" width="100"> <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /> </svg> </a>

Guess what happens, clicking on the SVG redirects you to https://www.example.com. Yes, you've guessed right!

Communication with SVG: pointers and events

Firstly, rid your SVG elements of any interfering clicks; set pointer-events: none;. This makes it possible for the object to function as a clickable link.

Anchor man(datorily) encapsulates SVG

Wrapping SVG like a baby in a blanket can be done by employing an anchor tag. Remember, the anchor's home attire constitutes display: block; for smooth clickability. For instance:

<a href="https://your-chosen-site.com" style="display: block; position: relative;"> <svg height="100" width="100" style="pointer-events: none;"> <!-- SVG drawing on a sunny day --> </svg> </a>

What you've done here is reserved the SVG's entire area as clickable territory. High five!

Past-tense compatibility: IE woes

If you're on a trip to the past with IE8<, you might encounter some mischievous behavior from SVG. But we got you; use conditioning tea (or comments) for web harmony. Layer your anchor ABOVE the SVG like so:

<div style="position: relative;"> <svg height="100" width="100"> <!-- SVG reliving the past --> </svg> <a href="https://www.timetravel-tours.com" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 10;"></a> </div>

The Unseen Ad blockers

Watch out for the invisible Ad Blockers, they might play tricks with your hover states. To be on the safe side, test your SVG links with these spunky ad-blocking extensions. You'll be ahead of the game!

Compatibility: A stitch in time...

Though it’s like finding a unicorn, some browsers don’t support SVG. In such mythical circumstances, provide them a fallback image for those adventurous users:

<object data="your-svg-image.svg" type="image/svg+xml"> <img src="your-plan-b-image.png" alt="Alternate universe" /> </object>

Portal parameters and high-sea SEO

Anchoring URL parameters

When SVGs double as clickable links, consider including query parameters. Observe:

<a href="https://www.yachting-world.com/yacht?name=titanic"> <svg height="100" width="100"> <!-- SVG sailing the azure waters --> </svg> </a>

Remember, your server better be ready to handle these precise parameters!

Accessibility: All aboard!

Roll out the red carpet for all types of users. Use aria-label or title attributes for a descriptive text for your SVGs. Making sure your SVG is prepared to host ALL browsers.