Problem with Eventlistener execution

Asked

Viewed 43 times

2

if((document.getElementById("avatarZica").innerHTML == "")){
        document.getElementById("avatarLegal").addEventListener("click", function(){
            document.getElementById("avatarZica").innerHTML = "<canvas class='emscripten' id='canvas' oncontextmenu='event.preventDefault()' height='400px' width='250px'></canvas>";

            var imported = document.createElement('script');
            imported.src = 'avatar/Release/UnityLoader.js';
            document.head.appendChild(imported);
            console.log(document.getElementById("avatarZica").innerHTML);
        });
    }

Code being used within the index.php file. I made the condition that if it was the first time the user clicked then he would run the above code creating the avatar to translate the content of the page, but if I click again it gives an error saying that the file already exists and hangs the page. Apparently the code is right and the condition too, but every time I click on the object it tries to create the file again and gives error on account of Unity. Thank you in advance.
Att,

1 answer

1


Change the order of the first two lines, thus the if is run every click. How do you have the if is run once and the addEventListener then always run under the same conditions.

document.getElementById("avatarLegal").addEventListener("click", function() {
  var avatarZica = document.getElementById("avatarZica");
  if ((avatarZica.innerHTML == "")) {
    avatarZica.innerHTML = "<canvas class='emscripten' id='canvas' oncontextmenu='event.preventDefault()' height='400px' width='250px'></canvas>";
    var imported = document.createElement('script');
    imported.src = 'avatar/Release/UnityLoader.js';
    document.head.appendChild(imported);
  }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.