JQuery + SVG Object: correctly capture click event

Ok, I'm trying to capture click events on menu items

Here is my html:

<nav> <ul> <li class="active left" id="profileLink"> <object type="image/svg+xml" data="public/img/nav/profile.svg"> <img src="public/img/nav/profile.png" alt="Blue Square"/> </object> </li> <li class="left" id="suggestionsLink"> <object type="image/svg+xml" data="public/img/nav/suggestions.svg"> <img src="public/img/nav/suggestions.png" alt="Blue Square"/> </object> </li> <li class="right" id="settingsLink"> <object type="image/svg+xml" data="public/img/nav/settings.svg"> <img src="public/img/nav/settings.png" alt="Blue Square"/> </object> </li> <li class="right" id="statisticsLink"> <object type="image/svg+xml" data="public/img/nav/statistics.svg"> <img src="public/img/nav/statistics.png" alt="Blue Square"/> </object> </li> <li class="middle" id="friendsLink"> <object type="image/svg+xml" data="public/img/nav/friends.svg"> <img src="public/img/nav/friends.png" alt="Blue Square"/> </object> </li> </ul> 

And here is the script I use:

  $("#wrapper").on("click", '#friendsLink', function(){ console.log('test'); loadFriends(); }); 

When I use a script to select a simple a-tag, it works fine, but on this svg object it doesn't work at all. Note that it works when you click on the padding area of ​​an li element. but not by clicking in the svg image area.

The message in this thread assumes that svg dom is different from html dom and therefore jquerys events fail.

jQuery Selector + SVG Incompatible?

How can I try to handle click events on svg elements?

Help is seriously appreciated

+4
source share
1 answer

If you want to use <object> , you will need to put click processing in the svg content, i.e. root element <svg> public / img / nav / profile.svg etc.

If you want to keep processing as is, you need to use the <image> element as the <svg> container, not the <object> element. This is due to its own limitations, such as a lack of scripting and a lack of backup.

A third option might be to place an absolutely positive transparent div over each svg element and handle onclick.

You will need to choose any solution that suits your needs.

+3
source

Source: https://habr.com/ru/post/1444172/


All Articles