For efficient use of Firebase, ensure to separate your HTML, JavaScript, and CSS code

I have a HTML page that includes JavaScript and CSS, but I want to host it on Firebase with separate files for JavaScript and CSS. While I understand how to do this locally, I'm unsure about the process when using Firebase.

P.S: Although I have experience with HTML, CSS, and JavaScript, my knowledge of Firebase is limited.

Code:

<!DOCTYPE html>
<html>
<head>
  <title>noname</title>
  <style type="text/css">
    input{
        resize: none;
        border-radius: 5px;
        size: 50px;
        height: 100%;
    }

    #main{
        text-align: center;
        padding: 20px;
        border: 5px solid;
        width: 50%;
        background-color: #c2e5ef;
        background-clip: border-box;

    }

    .button{
        color: #fff;
        background-color: #3fb2bf;
        margin: 10px 2px;
        border: none;
        font-size: 20px;
        width: 100px;
        height: 50px;
        border-radius: 15px
    }

    #login-div{
        text-align: center;
    }

    #logout-div{
        text-align: center;
    }
  </style>
</head>
<body>
 <div id="main">    
   <div id="login-div">
     <label><b style="font-size: 20px;">Username:<input type="text" name="username" id="username" placeholder="Enter Username"><br>
     </label>
     <br>

     <label>Password:<input type="text" name="password" id="password" placeholder="Enter Password"></label><br>

     <input type="button" name="login" value="Login" class="button" onclick="login()">
     </div>

     <div id="logout-div">
     <p>you are logged in</p>
     <input type="button" name="logout" value="Logout" class="button"  onclick="logout()">
    </div>

    <script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>

    <script type="text/javascript">
        var config = {
            apiKey: "AIzaSyDf4ndBB-CXJwaYVLXXQacFmX3O9eZbUZk",
            authDomain: "first-b14b2.firebaseapp.com",
            databaseURL: "https://first-b14b2.firebaseio.com",
            projectId: "first-b14b2",
            storageBucket: "first-b14b2.appspot.com",
            messagingSenderId: "103220354303"
        };
        firebase.initializeApp(config);

        firebase.auth().onAuthStateChanged(function(user) {
          if (user) {
            document.getElementById("login-div").style.display="none";
            document.getElementById("logout-div").style.display="block";
          } else {
            document.getElementById("login-div").style.display="block";
            document.getElementById("logout-div").style.display="none";
          }
        });

        function login(){
            var email=document.getElementById("username").value;
            var pass=document.getElementById("password").value;

            firebase.auth().signInWithEmailAndPassword(email, pass).catch(function(error) {
                var errorCode = error.code;
                var errorMessage = error.message;

                window.alert("error");
            });
        }

        function logout(){
            firebase.auth().signOut().then(function() {
            }).catch(function(error) {
            });
        }
     </script>
  </div>    
 </body>
</html> 

Answer №1

Creating a Firebase project involves setting up three distinct files: index.html, main.js, and style.css. These files need to be linked together properly for the project to function.

Let's start with the style.css file:

input{
    resize: none;
    border-radius: 5px;
    size: 50px;
    height: 100%;
}

#main{
    text-align: center;
    padding: 20px;
    border: 5px solid;
    width: 50%;
    background-color: #c2e5ef;
    background-clip: border-box;

}

.button{
    color: #fff;
    background-color: #3fb2bf;
    margin: 10px 2px;
    border: none;
    font-size: 20px;
    width: 100px;
    height: 50px;
    border-radius: 15px
}

#login-div{
    text-align: center;
}

#logout-div{
    text-align: center;
}

The JavaScript functionalities are then transferred from the HTML file to the main.js file:

var config = {
    apiKey: "AIzaSyDf4ndBB-CXJwaYVLXXQacFmX3O9eZbUZk",
    authDomain: "first-b14b2.firebaseapp.com",
    databaseURL: "https://first-b14b2.firebaseio.com",
    projectId: "first-b14b2",
    storageBucket: "first-b14b2.appspot.com",
    messagingSenderId: "103220354303"
};
firebase.initializeApp(config);

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    document.getElementById("login-div").style.display="none";
    document.getElementById("logout-div").style.display="block";
  } else {
    // No user is signed in.
    document.getElementById("login-div").style.display="block";
    document.getElementById("logout-div").style.display="none";
  }
});

function login(){
    var email=document.getElementById("username").value;
    var pass=document.getElementById("password").value;

    firebase.auth().signInWithEmailAndPassword(email, pass).catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;

        window.alert("error");
        // ...
    });
}

function logout(){
    firebase.auth().signOut().then(function() {
        // Sign-out successful.
    }).catch(function(error) {
        // An error happened.
    });
}

Finally, the remaining content goes into the index.html file. Make sure to import both the style.css and main.js:

<!DOCTYPE html>
<html>
<head>
  <title>noname</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
 <div id="main">    
   <div id="login-div">
     <label><b style="font-size: 20px;">Username:<input type="text" name="username" id="username" placeholder="Enter Username"><br>
     </label>
     <br>

     <label>Password:<input type="text" name="password" id="password" placeholder="Enter Password"></label><br>

     <input type="button" name="login" value="Login" class="button" onclick="login()">
     </div>

     <div id="logout-div">
     <p>you are logged in</p>
     <input type="button" name="logout" value="Logout" class="button"  onclick="logout()">
    </div>

    <script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>

    <script src="main.js"></script>
  </div>    
 </body>
</html> 
  1. Note that using relative imports for files like style.css and main.js enables the project to work locally and when deployed.

  2. To avoid issues, refrain from opening the file directly in your browser. Instead, use firebase serve to host the file locally and firebase deploy for deployment on Firebase Hosting.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to customize the appearance of radio buttons to have distinct backgrounds when selected and unselected?

One of the features on my website is the ability to choose from various colors, and I would like for the selected color to be highlighted. Shown below is an image depicting the current state: I would like to transform it to look like this: Thank you in ...

The Bootstrap validator triggers the form submission only after the second click

When I click on the submit button, I am attempting to submit a form that has its default action prevented and first checks a condition before proceeding. Below is the code snippet: $('#payment-form').bootstrapValidator({ live: 'dis ...

Is there a way to align a div to the center of the BODY element instead of its parent in

I have a sticky navigation bar with the tab "categories" that reveals the dropdown menu "categoriesDropdown" when hovered over. I want the dropdown menu to span the width of the screen and be centered on it. I also need the dropdown menu to stick to ...

Retrieve the highchart data from a PHP database table

Is there a way to display every row of data from my table in highcharts using PHP to JavaScript for each row? <script> series: [{ name: 'Instant Noodles', data: [<?php foreach ($query as $row){echo $row['noo ...

Activate the class when clicked

I am facing a minor issue with the JavaScript onClick function. I need a function that will target a specific class, like .modal. Currently, it looks like this <div class="modal" onclick="modalFix()"> <p>here is some text</p> </div> ...

What is the best way to execute a script on the homepage just one time?

I need some assistance with a script that should only run when a visitor arrives at my site for the first time. I want all content to be hidden initially and then revealed in a visually appealing way when the visitor clicks a button. However, I do not want ...

What is the best way to customize the styles of Material UI V5 Date Pickers?

Attempting to customize Mui X-Date-Pickers V5 through theme creation. This particular component is based on multiple layers. Interested in modifying the borderColor property, but it's currently set on the fieldset element, so need to navigate from Mu ...

Tips for designing a button that can execute a JavaScript function repeatedly

My goal is to rotate the numbers clockwise when the rotate button is clicked. I have included all the relevant code. I have created a button that triggers a javascript function when clicked. The problem is that the function only rotates the numbers once. ...

Enhance Your Website with a jQuery Plugin for Dynamic Updates to ElementsgetPost

Is there a way to update the content inside an element by passing a new value to the public method updateText? Currently, when I try to pass a new string to the updateText method and click the button, only the method name is received as an argument instea ...

Utilization of Chrome browser extensions within Chrome applications

Do chrome extensions work in chrome apps without any additional configuration needed in the manifest file? ...

Transform JSON data into a string separated by commas with an array embedded within

I've been trying to work with a JSON data but can't seem to convert it as needed. Here is the JSON structure: {"domiciles":[{"country":"AF"},{"country":"AX"},{"country":"AL"}],"investor":[{"type":"ii"},{"type":"pi"}]} It's stored in sessio ...

Unable to update div CSS using button click functionality

I have been working on this HTML/CSS code and I am trying to change the style of a div using a JavaScript button click event so that the div becomes visible and clickable. However, despite my efforts, it doesn't seem to be working as expected. Whenev ...

Blocked the loading of scripts due to non-compliance with the Content Security Policy directive

Encountering an error with externally loaded scripts: Refusing to load the script 'https://code.jquery.com/jquery-3.4.1.slim.min.js' due to violating the Content Security Policy directive: "script-src 'self' https://ajax.googlea ...

Determining the positioning of a tablet with a JavaScript algorithm

We are currently working on developing an HTML5/JavaScript application specifically designed for tablet devices. Our main goal is to create different screen layouts for landscape and portrait orientations. Initially, we attempted to detect orientation cha ...

Angular Material -md-grid-list display layout

I am currently working on implementing md-grid-tile from Angular Material. However, I am encountering an issue where the content within the md-grid-tile is aligned in the center. How can I adjust this to start aligning from the left instead? <md-co ...

Discover the method for retrieving the upcoming song's duration with jplayer

Hey there, I have a question regarding the jPlayer music player. Currently, I am able to retrieve the duration of the current song using the following code snippet: $("#jquery_jplayer_1").data("jPlayer").status.duration; However, I now want to obtain t ...

Transform a PDF document into a Google Doc utilizing the capabilities of the Google Drive API version 3

I successfully uploaded a PDF file to Google Drive using a node server. However, I am struggling to find a way to convert it to a Google Doc format so that it can be downloaded later as a DOCX document. Here is the code snippet I've been working with ...

What is the best way to arrange card-columns in a horizontal order?

My smart-scrolling list of cards uses the card-columns style, but I find it frustrating that they are ordered top to bottom like this: 1 4 7 2 5 8 3 6 9 This vertical ordering becomes impractical when dealing with a large number of items. When I have 50 ...

PHP code for displaying images on the same level

Is there a way to position images side by side in PHP? For example: image image image image. Currently, with the following code: print "</h2><br><a href='form.php'><img src=***.jpg width=100 height=100 /><br> ...

Achieving a Banner-Like Background Image Using CSS

I've been studying various website source codes, but I'm struggling to achieve a specific effect. I want to have an image as the background that sits behind everything on the page. However, I don't want the entire background to be covered by ...