1

In a JavaScript build, I have a hyperlink the user can click to send a message. When this link is clicked, attributes on that anchor tag are sent to a click event listener, which uses those attribute values to fill in portions of the message (where the message came from, etc.).

The problem: the anchor tag contains a nested <svg> element (small image). If the user clicks the anchor text, no problem, message sends with attribute data. But if the user clicks the <svg> image next to the anchor text, these attributes don't get sent, causing errors:

Anchor tag:

 <a class="my-anchor-class"
    my-attribute-id="{{ thing.id }}"
    my-attribute-title="{{ thing.title }}""
    href="#myHref">
     <svg>
         <use xlink:href="#myMessageSvg"/>
     </svg>    
     Send Me A Message
 </a>

Click event listener:

document.addEventListener('click', function (event) {
    var myElement = event.target;

    if (myElement.classList.contains('my-anchor-class')) {
        event.preventDefault();

        var myId = stripTheHtml(myElement.getAttribute('my-attribute-id'));
        var myTitle = stripTheHtml(myElement.getAttribute('my-attribute-title'));

        messages.setAttribute('action', MY_ACTION + myId);
        messagesTitle.innerHTML = 'Re: ' + myTitle;
    }
});

When <a>'s Send Me A Message text is clicked, all works fine. But if the <svg> image is clicked instead, attribute values don't get sent and action fails. I've tried adding the same attributes and class from <a> onto the <svg> element to no avail - still the same error. Does anyone know how to get a click of my <svg> image to work the same as clicking its parent's <a> text?

0

1 Answer 1

2

Check the event target for the element tagName. If it is not 'A', use the target's parent element as the source. Otherwise, the target must be the correct element.

Note I set the event handler on the anchor tag itself.

document.querySelector('.my-anchor-class').addEventListener('click', function(event) {
  event.preventDefault();
  let myElement = event.target;
  while (myElement.tagName !== 'A') {
    myElement = myElement.parentElement;
  }
  console.log(myElement.getAttribute('my-attribute-id'));

});
<a class="my-anchor-class" my-attribute-id="thing.id" my-attribute-title="thing.title" href="#myHref">
  <svg version="1.1" baseProfile="full" width="75" height="75" xmlns="http://www.w3.org/2000/svg">
  <rect width="100%" height="100%" fill="black" />
  <circle cx="0" cy="0" r="60" fill="blue" />
</svg> Send Me A Message
</a>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.