0

I have two Javascript files, one is a react wrapper, the other is raw Javascript/html that is loaded in the react wrapper because the Javascript/html is older code. In the Javascript/html code I try to attach event listeners to each button in a <ul>:

const previewItem = document.getElementsByClassName("previewItem");
        for (let i = 0; i < previewItem.length; i += 1) {
            previewItem[i].addEventListener('click', function(e) {
                var event = new Event('previewItem');
                previewItem[i].dispatchEvent(event);
            });
        }

And then in the react wrapper I handle the event like this:

const handlePreviewItem = e => {
            this.showCompilationModal(
                e.target.getAttribute('data-previewId'),
            );
        };

        const previewItem = document.getElementsByClassName('previewItem');
        for (let i = 0; i < previewItem.length; i += 1) {
            previewItem[i].addEventListener('previewItem', handlePreviewItem);
        }

The problem occurs because onload the dom might look something like this:

<ul>
    <li><button data-previewId="1"></button></li>
    <li><button data-previewId="2"></button></li>
    <li><button data-previewId="3"></button></li>
</ul>
<ul>
    <li><button data-previewId="4"></button></li>
</ul>

and after dragging from one list to another it could look like this:

<ul>
    <li><button data-previewId="1"></button></li>
    <li><button data-previewId="2"></button></li>
</ul>
<ul>
    <li><button data-previewId="3"></button></li>
    <li><button data-previewId="4"></button></li>
</ul>

After dragging from the top list to the bottom list and pressing the button with data-previewId="3", the e.target in showCompilationModal is actually the button after it in the dom which is data-previewId="4" and it causes a bug. I can't figure out why or how this happens.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
EdTheSped
  • 35
  • 5
  • 2
    Your problem could be resolved (and your code greatly simplified) if you used [event delegation](https://javascript.info/event-delegation) with the parent `ul` elements instead of the child `li` elements because then it wouldn't matter which list an `li` was in. Also [never use `.getElementsByClassName()` again](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474). – Scott Marcus Mar 20 '20 at 18:25
  • 1
    Thanks, I got it to working using what you suggested! – EdTheSped Mar 20 '20 at 18:52
  • Also not sure why you are binding events like that in react. – epascarello Mar 20 '20 at 19:26

0 Answers0