JS event propagation on svg works with class not id

38 Views Asked by At

We are setting up event propagation for our website, to allow links in dynamically inserted content to be active as soon as they are inserted. I am encountering a weird quirk with stand alone svg elements.

If I target the id of the svg the function fails, but if I target the class of the svg is works.

HTML for one of the standalone svg

<svg id="burger" class="menubtn" height="32" style="enable-background:new 0 0 32 32" width="32" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"><path d="M4 10h24a2 2 0 0 0 0-4H4a2 2 0 0 0 0 4zm24 4H4a2 2 0 0 0 0 4h24a2 2 0 0 0 0-4zm0 8H4a2 2 0 0 0 0 4h24a2 2 0 0 0 0-4z"/></svg>

JS for the event propagation (stripped down to essentials)

$('mstrwrap').addEventListener('click', function(e) {
  // set eventlisteners for all A HREF links
  if (e.target.nodeName === 'A') {
    // all the a href links
  }
  
  // check if nav menu icon - WORKS
  else if (e.target.classList.contains('menubtn')) {
    opennavbar();
  }

  // check if nav menu icon - DOES NOT WORK
  else if (e.target.id.includes('burger')) {
    opennavbar();
  }
}

While using class works and thus the page works, I am stumped as to why ID does not work when class does.

1

There are 1 best solutions below

0
Tom On

As mentioned in the comment by @Kaiido , it seems the issue was clicking on paths vs empty space.

We ended up wrapping the svg and assigning the ID to the wrapper (both SPAN and DIV worked in our tests). And then rewrote the event propagation to use closest().

html

<span id="burger"><svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="32" height="32" class="menubtn"><path d="M4 10h24a2 2 0 0 0 0-4H4a2 2 0 0 0 0 4zm24 4H4a2 2 0 0 0 0 4h24a2 2 0 0 0 0-4zm0 8H4a2 2 0 0 0 0 4h24a2 2 0 0 0 0-4z"/></svg></span>

js

else if (e.target.closest('#burger')) {
  opennavbar();
}