Row 36: Uncaught Typeerror: Cannot read Property 'addeventlistener' of null

Asked

Viewed 195 times

0

Whoa, what’s up, man? I’m doing a various firebase test project. Because he’s making the following mistake:

Uncaught TypeError: Cannot read property 'addEventListener' of null

This error is being given on line 36 of my javascript code:

var firebaseConfig = {
  apiKey: "0",
  authDomain: "0",
  databaseURL: "0",
  projectId: "0",
  storageBucket: "0",
  messagingSenderId: "0",
  appId: "0",
  measurementId: "0"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

var firestore = firebase.firestore();
const outputHeader = document.querySelector("#numeroOutput");
const inputTextFieldNome = document.querySelector("#nome");
const inputTextFieldIdade = document.querySelector("#idade");
const saveButton = document.querySelector("#mandar");

saveButton.addEventListener("click", function () {
  const nome = inputTextFieldNome.value;
  const idade = inputTextFieldIdade.value;
  console.log("Estamos dalvando o seu numero");
  const docRef = firestore.collection("usuarios/").doc(nome);
  docRef.set({
    Idade: idade
  }).then(function () {
    console.log("Salvo com sucesso!");
  }).catch(function (error) {
    console.log("Peguei um erro", error);
  });
});

var uploader = document.querySelector("#uploader");
var fileButton = document.querySelector("#fileButton");
fileButton.addEventListener("change", function (e) {
  //Get File
  var file = e.target.files[0];
  //Storage Reference
  var storageRef = firebase.storage().ref("txts/" + file.name);
  //Upload File
  var task = storageRef.put(file);
  //Update Progress Bar
  task.on("state_changed",
    function progress(snapshot) {
        var percentage =  snapshot.bytesTransferred / snapshot.totalBytes * 100;
        uploader.value = percentage;
    },
    function error(err) {

    },
    function complete() {

    });
});

The firebaseConfig is reset because I put it like this so I can post. And my HTML code is as follows:

<!DOCTYPE html>
<html lang="pt-br">

<head>
    <meta charset="utf-8">
    <title>Firebase</title>

    <style media="screen">
        body{
            display: flex;
            min-height: 100vh;
            width: 100%;
            padding: 0;
            margin: 0;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }
        #uploader{
            -webkit-appearance: none;
            appearance: none;
            width: 50%;
            margin-bottom: 10px;
        }
    </style>


    <script src="https://www.gstatic.com/firebasejs/7.15.4/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.15.4/firebase-firestore.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.15.4/firebase-storage.js"></script>
</head>
</head>

<body>

    <h1 id="numeroOutput">Firebase</h1>
    <h2>Firestore</h2>
    Nome : <input type="textfield" id="nome"><br>
    Idade : <input type="textfield" id="idade"><br>
    <button id="mandar">Enviar!</button>
    <script src="./app.js"></script>

    <br>

    <h2>Storage</h2>
    <progress value="0" max="100" id="uploader">0%</progress><br>
    <input type="file" value="upload" id="fileButton" />
</body>

</html>

Help me please!

  • By error message it is possible to deduce that the variable fileButton is as the value null. But the code to start it is correct, it is possible that your Javascript is running before the DOM is loaded, so it does not find the element #fileButton. Try to put your code inside a function and then invoke that function in the event onload of your page, which is fired when the DOM is loaded completely.

  • Important you [Dit] your question and explain objectively and punctually the difficulty found, accompanied by a [mcve] of the problem and attempt to solve. To better enjoy the site, understand and avoid closures and negativities worth reading the Stack Overflow Survival Guide in English.

1 answer

1


Do as user140828 said: your script is running before the DOM is loaded. Just put your script inside window.onload which ensures that the code will be executed after the DOM is loaded:

window.onload = function(){
  var firebaseConfig = {
    apiKey: "0",
    authDomain: "0",
    databaseURL: "0",
    projectId: "0",
    storageBucket: "0",
    messagingSenderId: "0",
    appId: "0",
    measurementId: "0"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);

  var firestore = firebase.firestore();
  const outputHeader = document.querySelector("#numeroOutput");
  const inputTextFieldNome = document.querySelector("#nome");
  const inputTextFieldIdade = document.querySelector("#idade");
  const saveButton = document.querySelector("#mandar");

  saveButton.addEventListener("click", function () {
    const nome = inputTextFieldNome.value;
    const idade = inputTextFieldIdade.value;
    console.log("Estamos dalvando o seu numero");
    const docRef = firestore.collection("usuarios/").doc(nome);
    docRef.set({
      Idade: idade
    }).then(function () {
      console.log("Salvo com sucesso!");
    }).catch(function (error) {
      console.log("Peguei um erro", error);
    });
  });

  var uploader = document.querySelector("#uploader");
  var fileButton = document.querySelector("#fileButton");
  fileButton.addEventListener("change", function (e) {
  //Get File
  var file = e.target.files[0];
  //Storage Reference
  var storageRef = firebase.storage().ref("txts/" + file.name);
  //Upload File
  var task = storageRef.put(file);
  //Update Progress Bar
  task.on("state_changed",
  function progress(snapshot) {
    var percentage =  snapshot.bytesTransferred / snapshot.totalBytes * 100;
      uploader.value = percentage;
    },
    function error(err) {
    },
    function complete() {
    });
  });
}

Browser other questions tagged

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