Search code examples
javascripthtmlfirebasematerialize

Blank page when using materialize framework


CONTEXT

I am trying some features of the Firebase platform. I built a very trivial html page, and tried different features: sign up, login, sign out, ... I have two pages: index.html and auth.js:

index.html

<html>
<head>


<title> First test </title>
<!-- Load library: The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js"></script>
<!-- Load library: Add additional services you want to use -->
<script src="https://www.gstatic.com/firebasejs/5.0.1/firebase-firestore.js"></script>
<!-- Load library: Authentification -->
<script src="https://www.gstatic.com/firebasejs/5.0.1/firebase-auth.js"></script>

<script>

var firebaseConfig = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  var firestore = firebase.firestore();
  firestore.settings({ timestampsInSnapshots: true });
  const auth = firebase.auth();
</script>



<link type="text/css" rel="stylesheet" href="css/materialize.css"  media="screen,projection"/> 
</head>

<body>
<!-- Add an element to the data storage -->

<div id ="modal-add-data" class='modal'>
  <div class='modal-content'>
    <h4> Add data </h4><br />
      <form id='add-data'>
        <div class = 'input-field'>
          <input type='data1' id="data1" />
          <label for='data1'> data1 </label>
        </div>
        <div class = 'input-field'>
          <input type='data2' id="data2" />
          <label for='data2'> data2 </label>
        </div>
            <button id='save-data' type='button'> Add</button>  
    </form>
  </div>
</div>



<!-- Authentificate a new user -->


<div id ="modal-signup", class='modal'>
  <div class='modal-content'>
    <h4> Sign Up </h4><br />
      <form id='signup-user'>
        <div class = 'input-field'>
          <input type='email' id="signup-email" />
          <label for='signup-email'> email adress </label>
        </div>
        <div class = 'input-field'>
          <input type='password' id="signup-password" />
          <label for='signup-password'> password </label>
        </div>
            <button id='signup-button' type='submit'>sign up</button>  
        </form>
  </div>
</div>

<!-- Sign out a user -->


<div id ="modal-signout", class='modal'>
  <div class='modal-content'>
    <h4> Log Out button </h4><br />
      <form id='signout-user'>
            <button id='signout-button' type='button'>sign out</button>  
        </form>
  </div>
</div>

<!-- Login a user -->


<div id ="modal-login", class='modal'>
  <div class='modal-content'>
    <h4> Login </h4><br />
      <form id='login-user'>
        <div class = 'input-field'>
          <input type='email' id="login-email" />
          <label for='login-email'> email adress </label>
        </div>
        <div class = 'input-field'>
          <input type='password' id="login-password" />
          <label for='login-password'> password </label>
        </div>
            <button id='login-button' type='submit'>login</button>  
        </form>
  </div>
</div>


<script  src='./auth.js' ></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
</body>

</html>


<!-- <script src="https://www.gstatic.com/firebasejs/5.0.1/firebase-storage.js"></script> -->

auth.js

// Listen for auth status changes
auth.onAuthStateChanged(user => {
  if (user) {
    console.log("user logged in: ", user);

  } else {

    console.log("user logged out");

  }


})    


        // Sign up function 

const signupForm = document.querySelector('#signup-user');

signupForm.addEventListener("submit", (e) => {

  e.preventDefault(); // avoid the page to refresh when we click signup

  // get user info from the id of the input
  const email = signupForm['signup-email'].value;
  const password = signupForm['signup-password'].value;
  auth.createUserWithEmailAndPassword(email, password).then( cred => {

      console.log(cred);
      const modal = document.querySelector('#modal-signup');
      console.log(modal)
      M.Modal.getInstance(modal).close();
      signupForm.reset();
      // div id
    });

});

        // Add data function 

const save = document.querySelector('#add-data');
  const docRef = firestore.collection("samples").doc("user_");
  const eventToListen = document.querySelector('#save-data');
  //const docRef = firestore.doc("samples/secondtest");

// The sign up variables and constants


  // All the functions 

  // Add some data in firestroe

  eventToListen.addEventListener("click", function()  {
      const inp1 = save['data1'].value;
      const inp2 = save['data2'].value;

      docRef.set({   // https://firebase.google.com/docs/firestore/manage-data/add-data?authuser=3
        lname: inp1,
        firstname: inp2,
        }).then(function() {

          console.log("Status saved");
        }).catch( function (error) {  

            console.log("Got an eror", error);

      });

  });


        // Login function 

const loginForm = document.querySelector('#login-user');


loginForm.addEventListener("submit", (e) => {

  e.preventDefault(); // avoid the page to refresh when we click signup

  // get user info from the id of the input
  const email = loginForm['login-email'].value;
  const password = loginForm['login-password'].value;
  auth.signInWithEmailAndPassword(email, password).then( cred => {

      console.log(cred.user)
      const modal = document.querySelector('#modal-login');
      M.Modal.getInstance(modal).close();
      loginForm.reset();
      // div id
    });

});



        // Logout function

const signoutForm = document.querySelector('#signout-button');

signoutForm.addEventListener("click", (e) => {

  e.preventDefault(); // avoid the page to refresh when we click signup
  // get user info from the id of the input
  auth.signOut()   

});

MY PROBLEM:

When I am importing the materialize framework, in the index.html file ( )

my page becomes blank. When I drop this import, then the page is loaded. Of course, I have downloaded the materialize frameworks files. When I drop this line

thanks a lot


Solution

  • So I took a closer look to your code.

    The main reason nothing shows up is because you are using modals and they aren't initialized nor opened.

    Here is some documentation about it: https://materializecss.com/modals.html

    You can try by adding the following javascript:

    document.addEventListener('DOMContentLoaded', function() {
        var elems = document.querySelectorAll('.modal');
        var instances = M.Modal.init(elems, { dismissible: false });
    
        var modal = document.querySelector('#modal-signup');
        M.Modal.getInstance(modal).open();
    });
    

    There are also other things that are wrong in your HTML and javascript:

    Here is a example with the authentification working (I didn't test the data part):

    index.html

    <html>
        <head>
            <title> First test </title>
    
            <!--Import Google Icon Font-->
            <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
            <!--Import materialize.css-->
            <link type="text/css" rel="stylesheet" href="css/materialize.min.css"  media="screen,projection"/>
    
            <!--Let browser know website is optimized for mobile-->
            <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        </head>
        <body>
            <!-- Add an element to the data storage -->
            <div id="modal-logged" class="modal">
                <div class="modal-content">
                    <h4> Add data </h4>
                    <form id="add-data">
                        <div class="input-field">
                            <input type="text" id="data1" />
                            <label for="data1">data1</label>
                        </div>
                        <div class="input-field">
                            <input type="text" id="data2" />
                            <label for="data2">data2</label>
                        </div>
                        <button id="save-data">Add</button>  
                    </form>
    
                    <h4>Logout button</h4>
                    <form id="signout-user">
                        <button id="signout-button" class="btn waves-effect waves-light" type="submit">sign out</button>  
                    </form>
                </div>
            </div>
            <!-- Authentificate or register user -->
            <div id="modal-connect" class="modal">
                <div class="modal-content">
                    <h4>Login / sign up</h4>
                    <form id="login-form">
                        <div class="input-field">
                            <input type="email" id="login-email" />
                            <label for="login-email">email address</label>
                        </div>
                        <div class="input-field">
                            <input type="password" id="login-password" />
                            <label for="login-password">password</label>
                        </div>
                        <button id="login-button" class="btn waves-effect waves-light" type="submit">login</button>
                        <button id="signup-button" class="btn waves-effect waves-light" type="submit">sign up</button>
                    </form>
                </div>
            </div>
    
            <!--JavaScript at end of body for optimized loading-->
            <script type="text/javascript" src="js/materialize.min.js"></script>
            <!-- Load library: The core Firebase JS SDK is always required and must be listed first -->
            <script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js"></script>
            <!-- Load library: Add additional services you want to use -->
            <script src="https://www.gstatic.com/firebasejs/5.0.1/firebase-firestore.js"></script>
            <!-- Load library: Authentification -->
            <script src="https://www.gstatic.com/firebasejs/5.0.1/firebase-auth.js"></script>
            <script src="https://www.gstatic.com/firebasejs/5.0.1/firebase-storage.js"></script>
            <script>
                // Your web app's Firebase configuration
                var firebaseConfig = {
                    apiKey: "",
                    authDomain: "",
                    databaseURL: "",
                    projectId: "",
                    storageBucket: "",
                    messagingSenderId: "",
                    appId: "",
                    measurementId: ""
                };
                // Initialize Firebase
                firebase.initializeApp(firebaseConfig);
                var firestore = firebase.firestore();
                firestore.settings({ timestampsInSnapshots: true });
                const auth = firebase.auth();
            </script>
            <script type="text/javascript" src="auth.js"></script>
        </body>
    </html>
    

    auth.js

    document.addEventListener('DOMContentLoaded', function() {
        var elems = document.querySelectorAll('.modal');
        var instances = M.Modal.init(elems, { dismissible: false });
    
        // Listen for auth status changes
        auth.onAuthStateChanged(user => {
            if (user != undefined) {
                M.toast({html:"Logged in"});
    
                var modal = document.querySelector('#modal-connect');
                M.Modal.getInstance(modal).close();
                modal = document.querySelector('#modal-logged');
                M.Modal.getInstance(modal).open();
            } else {
                M.toast({html:"Logged out"});
    
                var modal = document.querySelector('#modal-logged');
                M.Modal.getInstance(modal).close();
                modal = document.querySelector('#modal-connect');
                M.Modal.getInstance(modal).open();
            }
        });
    
        // The sign up variables and constants
        const loginBtn = document.querySelector('#login-button');
        const signUpBtn = document.querySelector('#signup-button');
        const signoutForm = document.querySelector('#signout-button');
        const save = document.querySelector('#add-data');
        const docRef = firestore.collection("samples").doc("user_");
        const eventToListen = document.querySelector('#save-data');
    
        // Sign up function 
        signUpBtn.addEventListener("click", (e) => {
            e.preventDefault(); // avoid the page to refresh when we click signup
    
            // get user info from the id of the input
            const loginForm = document.querySelector('#login-form');
            const email = loginForm['login-email'].value;
            const password = loginForm['login-password'].value;
            auth.createUserWithEmailAndPassword(email, password).catch(function(error) {
                // Handle Errors here.
                var errorCode = error.code;
                M.toast({html:error.message});
            }).then( cred => {
                loginForm.reset();
            });
        });
    
        // Add data function 
        // Add some data in firestore
        eventToListen.addEventListener("click", function()  {
            const inp1 = save['data1'].value;
            const inp2 = save['data2'].value;
    
            docRef.set({   // https://firebase.google.com/docs/firestore/manage-data/add-data?authuser=3
                lname: inp1,
                firstname: inp2
            }).then(function() {
                M.toast({html:"Status saved"});
            }).catch( function (error) {
                M.toast({html:error.message});
            });
        });
    
        // Login function 
        loginBtn.addEventListener("click", (e) => {
            e.preventDefault(); // avoid the page to refresh when we click signup
    
            // get user info from the id of the input
            const loginForm = document.querySelector('#login-form');
            const email = loginForm['login-email'].value;
            const password = loginForm['login-password'].value;
            auth.signInWithEmailAndPassword(email, password).catch(function(error) {
                // Handle Errors here.
                var errorCode = error.code;
                M.toast({html:error.message});
            }).then( cred => {
                loginForm.reset();
                // div id
            });
        });
    
        // Logout function
        signoutForm.addEventListener("click", (e) => {
            e.preventDefault(); // avoid the page to refresh when we click signup
            // get user info from the id of the input
            auth.signOut();
        });
    });