brunokoji
brunokoji

Reputation: 13

Window Click Event Javascript not work the first click

I have a question, this code works but the first click does not work, when I click the first time window.open does not work, only after second click it works.

let t = setInterval(function(){
        let x = document.createElement('p');
        x.className = 'text-style';
        x.innerHTML = games[cont];
        box.appendChild(x);
        if(cont >= games.length - 1){
            clearInterval(t);
        }
        cont++;
    },50);
    let gamesT = document.getElementsByClassName('text-style');
    window.addEventListener('click', function(){
        for(let i = 0; i < gamesT.length; i++){
            gamesT[i].addEventListener('click', function(){
                window.open('https://www.google.com/search?q=' + gamesT[i].innerHTML, '_blank');
                });
        }
    });

Upvotes: 0

Views: 1186

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36584

That is because when the element is created it doesnot have event listener attached. You can fix that by creating a function and pass that click. And also call it in each interval

let gamesT = document.getElementsByClassName('text-style');
let t = setInterval(function(){
        let x = document.createElement('p');
        x.className = 'text-style';
        x.innerHTML = games[cont];
        box.appendChild(x);
        if(cont >= games.length - 1){
            clearInterval(t);
        }
        cont++;
        addListeners();
    },50);

function addListeners(){
    for(let i = 0; i < gamesT.length; i++){
        gamesT[i].onclick = function(){
              window.open('https://www.google.com/search?q=' + gamesT[i].innerHTML, '_blank');
         }
     }
}
window.addEventListener('click', addListeners);

Upvotes: 2

Related Questions