html5sortable icon indicating copy to clipboard operation
html5sortable copied to clipboard

Adding an event listener to multiple elements

Open tbhockey opened this issue 6 years ago • 3 comments

I'm opening this issue because:

This is likely a misunderstanding on my part rather than a bug.

I am unsure how to add a listener to multiple instances using the same selector. The docs say: https://github.com/lukasoppermann/html5sortable#events

Events can be listened on any element from the group (when using connectWith), since the same event will be dispatched on all of them.

But when I try this using connectWith or acceptFrom, and then add a listener on the first element sortable('.selector')[0].addEventListener..., it is still only that first element that seems to have a listener.

I've temporarily "solved" this just by looping through each element and adding a listener manually, but surely I'm missing a better way?

supporting information:

  • I use sortable version: 0.9.17
  • I tested in the following browser (incl. versions): Safari 13.0.4
  • Windows, OS X/macOS, or Linux?: macOS

example

<ol class="parent-list">
  <li>
    <ol class="child-list">
      <li></li>
      <li></li>
    </ol>
  </li>
</ol>
<ol class="parent-list">
  <li>
    <ol class="child-list"><!-- this element is not firing events -->
      <li></li>
      <li></li>
    </ol>
  </li>
</ol>

sortable('.child-list', {
  acceptFrom: '.child-list',
});

sortable('.child-list')[0].addEventListener('sortupdate', function(e) {
  console.log('foo');
});

tbhockey avatar Mar 10 '20 20:03 tbhockey

Hey @tbhockey,

I am not working with the plugin anymore, but if I see it correct you are doing everything correct. In Javascript you can not attach EventListeners to multiple element without a loop, because it only works on a node and not a nodeList. (If I am not mistaken).

I hope this clarifies your question. If you would like to send a PR to improve the documentation I would be very happy to merge it.

lukasoppermann avatar Mar 11 '20 08:03 lukasoppermann

@lukasoppermann ah ok, thank you for the clarification. I think i was just misunderstanding the one little sentence in the docs. :)

tbhockey avatar Mar 11 '20 12:03 tbhockey

Great if you have an idea how to improve it in the docs or if you want to send a PR to allow for binding events via the api, feel free. 😉

lukasoppermann avatar Mar 11 '20 12:03 lukasoppermann