Home > Software design >  Handling the eventlistener
Handling the eventlistener

Time:12-08

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I will try to explain what is the exact issue that is happening below.

Here is your code

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

// You are adding a click event listner to your DOM
// This will trigger when ever you click on your html page
document.addEventListener('click', function () { // Code Section 1
  console.log('this is a console log from first click event listner');
  homepage.innerHTML = `<div> hello what's your name? </div>`;

  // You are adding an another click event listner to your DOM
  document.addEventListener('click', function () { // Code Section 2
    
    console.log('this is a console log from second click event listner');
    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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

You have added a click event listner to your document using

document.addEventListener('click', function () {

(Refer Code Section 1 from the comment added in above code).

What this will do?

This will execute the entire set of code which is written inside that block when ever you click any where on your html page.

What is happening inside that code block?

Inside that code block, you are adding an another click event to the document using

document.addEventListener('click', function () {

(Refer Code Section 2 from the comment added in above code).

What happened till now?

You are now adding a click event listner, when ever the user clicks on the html application.

So what does this means?

This simply means that your code will keep on adding new click event listners whenever the user clicks on the application. So if the user click one time on the app, there will be two click event listner. If the user click the third time, one more event listner will be added, so that the total event listner will be three. This will keep on incrementing. This is happening because, you are keep on adding new click event listner when the pervious event listners exist.

So What wrong did happen? How to stop preventing the accumulation of event listners?

You have to revove the event listners before adding new event listners. You can make use of EventTarget.removeEventListener() for this purpose.

Implemetation using EventTarget.removeEventListener()

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

function listnerFunction() {
  console.log('first click event triggered');
  homepage.innerHTML = `<div> hello what's your name? </div>`;

  // Removing the first event listner
  document.removeEventListener('click', listnerFunction);
  
  // Adding second event listner
  document.addEventListener('click', secondListnerFunction);
}

function secondListnerFunction() {
  console.log('second click event triggered');
  homepage.innerHTML = `<div>
                            my name is <br> 
                            <input id="name"> </input> <br>
                            <button> submit </button>
                          </div>
                          `;
  // Removing the second event listner
  document.removeEventListener('click', secondListnerFunction);
}

// You are registering click event to your complete html
document.addEventListener('click', listnerFunction);
#homepage {
  text-align: center;
}
<div id="homepage"> click to change the content </div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Explantion

Here I have added a click event listner function to the document using

document.addEventListener('click', listnerFunction);

What this will do?

This will trigger the function listnerFunction when the user clicks on the document.

Handling the second click from the first click event listner

Inside the first click event listner listnerFunction I have updated the innerHTML of your selected element. After this I have removed the first click event listner with

document.removeEventListener('click', listnerFunction);

There after I registered second click event listner with

document.addEventListener('click', secondListnerFunction);

What happens inside second click event listner?

Inside the second click event listner, I updated the innerHTML of your required target and I have removed the click event listner using

document.removeEventListener('click', secondListnerFunction);

This removing of the click event listner is required, after this whenever the user clicks the document, no events will be triggered and hence the user can use the app seamlessly.

Happy coding :)

CodePudding user response:

const texts = [
    "How are you?",
    "Tired of studying?",
    "Too long enough"
];

let textTake = 0;

document.addEventListener('click', ()=>{
    if(textTake >= texts.length) textTake = 0; ​ 
    document.getElementById("homepage").innerText = texts[textTake];
    textTake  ;
});

CodePudding user response:

Here is a starter for you,

Good luck

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();
    };
});
  • Related