Search code examples
javascripthtmlonclicklistenerdocumentevent-listener

Handling the eventlistener


I'm working on my college's project and it's kind of like a web-text-based game. So I'm interested in a click event on a document to change the context and I did it with the code below.

The problem is that it keeps repeating everything and wont allow typing in the input.

const homepage = document.querySelector('#homepage')

document.addEventListener('click', function() {
  /*I console.log to check that the function is still repeating*/
  console.log('check')
  homepage.innerHTML = `<div> hello what's your name? </div>`
  document.addEventListener('click', function() {
    homepage.innerHTML = `<div> my name is <br> 
<input id="name"> </input> <br>
<button> submit </button<
`
  })
})
#homepage {
  text-align: center;
}
<div id="homepage"> click to change the content </div>


Solution

  • Here is a starter for you:

    const homepage = document.querySelector('#homepage');
    
    let html = [
        "hello what's your name?",
        'my name is <br> <input id="name"> <br> <button> submit </button>'
    ];
    
    document.addEventListener('click',function(){
        if (html.length) {
            homepage.innerHTML = html.shift();
        };
    });