0

The input where i get the value is attached with the keyPressed function, so when the person clicks the event runs, when i try to make a second task, the event does not fires.

const container = document.getElementById('container');
document.getElementById("textNode").addEventListener("keypress", keyPressed);
let button = document.querySelectorAll('button');
function keyPressed() {
    if (event.which === 13) {

        if (this.value == '') {
            return alert('Não é possivel inserir vazio')
        }

        console.log('stuff')
        let text = this.value;
        let novaTarefa = `<div class="task">
                        <h2>${text}</h2>
                        <button onclick="deleteThis">feita!</button>
                    </div>`;

        container.innerHTML += novaTarefa;
    }
}

i can create a new task once, but then it appears as if the reference were lost,

However, but it does works with this other code of mine:

function keyPressed() {
    if (event.which === 13) {

        if(this.value == ''){
            return alert('Não é possivel inserir vazio')
        }

        let h2 = document.createElement("h2");
        let text = document.createTextNode(this.value);
        let btn = document.createElement('button');
        let textBtn = document.createTextNode("feita!");

        h2.appendChild(text);
        btn.appendChild(textBtn);
        let att = document.createAttribute("class"); 
        att.value = "task";  

        let div = document.createElement("div");
        div.appendChild(h2);
        div.appendChild(btn);
        div.setAttribute('class', 'task')

        container.appendChild(div);
        text = '';
    }

}

salsinga
  • 1,957
  • 1
  • 14
  • 26
  • This has nothing to with the template literals and all with `innerHTML`. The `#textNode` is part of the `#container`, right? – Bergi Feb 06 '20 at 12:24
  • page gives a refresh, then it loses the event listener – kaiqueAMoraes Feb 06 '20 at 12:26
  • yes, i made a codepen: https://codepen.io/kaiqueamoraes/pen/ZEGEXJe – kaiqueAMoraes Feb 06 '20 at 12:28
  • i was able to resolve, but the thing is, i wasn't recreating an innerHTML but actually adding it to the container, why is that destroying the child elements – kaiqueAMoraes Feb 06 '20 at 12:49
  • `container.innerHTML += novaTarefa;` is short for `container.innerHTML = container.innerHTML + novaTarefa;`, which does completely destroy and recreate the elements. – Bergi Feb 06 '20 at 13:02

0 Answers0