0

My goal is the following: there is a div with an editable span inside, when a dot is typed inside the span I want to add a new span adyacent to it, focus the new span and continue writing in that one, which should have the same behaviour.

The behaviour I describe actually works, but every time a new span is added, the previous loses every event listener I had added.

The body of my html file looks like this

<body>
    <div id="search">
        <span class="tag">person</span>.
    </div>
    <script src="myscript.js"></script>
</body>

where myscript.js creates a first span (span1) inside #search and then adds the folowing event listeners


function createTag(event) {
    if (event.key == '.') {
        let color = search.childElementCount;
        let span = document.createElement('span');
        span.setAttribute('style', 'color:' + palette[color]);
        span.className = 'tag';
        span.contentEditable = true;
        search.innerHTML = search.innerHTML + '.';
        search.appendChild(span)
        span.addEventListener('keyup', createTag);
        span.addEventListener('blur', deleteTag);
        span.focus()
    };
};

function deleteTag() {
    if (this.innerText.length == 0 && search.childElementCount > 2){
        search.removeChild(this);
    }
}

span1.addEventListener('keyup', createTag);
span1.addEventListener('blur', deleteTag);

miguelsxvi
  • 27
  • 6
  • 1
    I'm pretty sure when you're modifying the innerHTML, you're forcing the browser to parse the HTML again and generate new elements. Those new elements won' have the same event listeners that the old ones had. You need to programmatically append the elements instead of modifying innerHTML directly – Abir Taheer Jun 27 '22 at 20:09
  • 1
    Yeah.. event listeners are bound to instances not bare objects. – EvgenyKolyakov Jun 27 '22 at 20:09
  • 1
    I agree to both first commentators. You should think about using event delegation which would solve your problem. – Johannes Wulf Jun 27 '22 at 20:11

0 Answers0