Uncaught Typeerror: Cannot read Property 'addeventlistener' of null

Asked

Viewed 540 times

1

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>javascript</title>
</head>

<style>
  body,
  html {
    font-size: 150%
  }
  
  body {
    color: #FFF;
    font-family: 'PT Sans', sans-serif;
    padding: 5%;
    font-size: 1.5em;
    background: #16A085
  }
</style>

<body>

  <link href="https://fonts.googleapis.com/css?family=PT+Sans:400,700" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-1.12.3.js" integrity="sha256-1XMpEtA4eKXNNpXcJ1pmMPs8JV+nwLdEqwiJeCQEkyc=" crossorigin="anonymous"></script>
  <script>
    $(function() {
      var test = $('div');

      var text1 = prompt('tag');
      var text2 = prompt('attributo');
      var text3 = prompt('valor');

      // crée un nouvel élément div id  
      var newDiv = document.createElement("textarea");
      newDiv.id = "test";
      var currentDiv = document.getElementById("reponse");
      document.body.insertBefore(newDiv, currentDiv);


      var newContent = document.createTextNode(".\/\/" + text1 + "[@" + text2 + "=\\\"" + text3 + "\\\"]");
      // ajoute le noeud texte au nouveau div créé
      newDiv.appendChild(newContent);




      // crée un nouvel élément bouton id  
      var btCopie = document.createElement("button");
      btCopie.id = "copy-button";
      var btCopy = document.getElementById("copy-button");
      document.body.insertBefore(btCopie, btCopy);
      var btCopieContent = document.createTextNode("copy1");
      btCopie.appendChild(btCopieContent);

    });

    var button = document.getElementById("copy-button");

    button.addEventListener("click", function(event) {
      event.preventDefault();
      test.select();
      document.execCommand("copy");
    });
  </script>

</body>

</html>

1 answer

0

The problem you have is that when you run var button = document.getElementById("copy-button"); the button has not yet been added to the DOM, since the $(function(){}) jQuery’s run after, despite being declared before. Note this example:

$(function() {
  console.log('Quando o DOM estiver pronto!');
});
console.log('Quando o script é carregado'); // eu corro primeiro!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Place the button code next to the jQuery code or also it inside $(function(){})

Browser other questions tagged

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