Like Button Using JavaScript and Firebase

If you are building a website for your personal blog then you can add a like button on every post. This will make your project better. If you have your own server then that is so easy but if you are building the project on GitHub pages or Google blogger then it is not an easy thing. In this article, I will show you how you can create a like button that can count likes in real-time using a firebase.


Project Demo

Every click on the like button is counted by the real-time database. We are using firebase as the real-time database for this project.

Main Theory

Every time when we click on the like button Firebase gets that signal. Before that, some calculation is done by the browser. At first, the browser collect data from firebase when a user loads the page. Then it shows that data to the user. When the user clicks on the button then the browser adds 1 with that number and that information gets stored in the firebase realtime database. Firebase is always connected with the browser and it sends any change of data to the browser. So, the browser is getting all new data.

How To Make

Here in this section, we are going to show all the steps you need to make this. Follow the steps below to make that. By following this processor you can implement this in any of your projects. The Github repository link is included so you can check the full project.

Create a new firebase project

Go to https://firebase.google.com and then sign in or sign up with your Google account. Then go to firebase console. And create a new firebase project and give it any supported name you want.

Add a google analytics code to your project if you want to monitor the traffic or user. You can turn off this feature if you don't want to use that. But I prefer to use this so I am using this on this project.

If you already have any Google Analytics property then you need to select that for this Firebase project. You can create a new property for this project.

Finally, build the full project. You have to wait for 10-15 seconds for the final setup. After that click on the 'continue button.


Register your Web App in firebase

In the project dashboard, you can find the web icon. Select your platform. Here we are building a project based on the web so we are going to select the web platform. Now give your project a name. The image is included below:

Copy Firebase SDK

After registering the web app in firebase you will get the SDK or Software Development Kit for your project. You just need some authentication code for this project. Copy the full SDK code and store it somewhere.


Create a Realtime Database for this project

We need a real-time database for counting each like at the same time from different users from different locations. Using firebase we can do that easily. You just need to go to the Realtime database section in the dashboard and create a new database. Select the database location for better performance.

Set the database in test mode because in this way you can test the application easily. You can change it any time. It always a better idea to select a test mode when the application is in the development process.

After creating the database copy the database URL. You will need the database URL to connect it with the main project. Click on the URL and copy it and then store it somewhere.


HTML code

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
rel="stylesheet" />
<div class="CountLike" id="Like Count">
<button class="button button1">
<i class="fa fa-heart"></i> Like <span class="counterStat">...</span>
</button>
</div>

Using this HTML code you can easily create a skeleton of that like button. You just need some CSS to make that look like a nice 'Like button'. Here I am sharing the CSS code with you.

CSS code

<style>
    .button {
        background-color: #4CAF50;
        /* Green */
        border: none;
        color: white;
        padding: 16px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        transition-duration: 0.4s;
        cursor: pointer;
    }
    
    .button1 {
        background-color: #f44336;
        color: white;
        border-radius: 20px;
        margin-bottom: 25px;
        box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
    }
    
    .button1:hover {
        background-color: #008CBA;
        color: white;
    }
    
    .counterStat {
        color: white;
        font-size: 16px;
    }
</style>

Using this CSS code you can make the button look nice and understandable for the user. You can also find different designs online. Just search on google and you can find many special designs. Now add JavaScript for different functionality.

JavaScript Code

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

    <!-- Initialize Firebase -->
    <script>
        var config = {
            apiKey: "Paste Your API Key provided by Firebase",
            authDomain: "Paste Your authDomain provided by Firebase",
            databaseURL: "Create a database and then paste the url of that database here",
            storageBucket: "Paste Your storageBucket provided by Firebase",
            messagingSenderId: "Paste Your messagingSenderId provided by Firebase"
        };
        firebase.initializeApp(config);
    </script>

    <script type="text/javascript">
        var dCounters = document.querySelectorAll('.CountLike');
        [].forEach.call(dCounters, function(dCounter) {
            var el = dCounter.querySelector('button');
            var cId = dCounter.id;
            var dDatabase = firebase.database().ref('Like Number Counter').child(cId);

            // get firebase data
            dDatabase.on('value', function(snap) {
                var data = snap.val() || 0;
                dCounter.querySelector('span').innerHTML = data;
            });

            // set firebase data
            el.addEventListener('click', function() {
                dDatabase.transaction(function(dCount) {
                    return (dCount || 0) + 1;
                });
            });
        });
    </script>

Here replace data with the Firebase SDK code you stored before. For example, change the API key with your SDK. Change the database URL with the URL you copied before from your project. I marked all those lines you have to change. Here is the code from my project:

Test the Like Button

Finally, run the project using a live server or something like that and then monitor the database. If everything is ok then the database should count each click. Check code again and try again if you face any bugs. Here is the GitHub Repository link of the full project. Just carefully replace SDK data with that code.


Conclusion

This is just a demo project. You can use this as a download counter, view counter, user counter, and many more. Using the same method you can actually build a real-time chat application. Just try to understand the code and how that code actually works. If you properly understand the code then you can build many real-time projects using firebase. Check our other articles on JavaScript.

2 Comments

  1. Bro plz. Make real time comment section using html Css js

    ReplyDelete
  2. Thank you for your tutorial, can you help me to make it different value for each post?
    i have javascript with same methode but for pageview, hope you can check it. https://cdn.statically.io/gh/yanuarzg/pv/main/pv.js

    ReplyDelete
Post a Comment
Previous Post Next Post