Skip to Content

How do you make a Like button?

How do you make a Like button?

A Like button allows users to show support or appreciation for content on a website or app with a single click. This popular feature seen on most social media platforms and across the web has become a staple in web design.

In this comprehensive guide, we will cover everything you need to know about making a custom Like button from scratch including:

  • The technical requirements for adding Like functionality
  • How to code the front-end button in HTML, CSS and JavaScript
  • Integrating the back-end with a server-side language like PHP
  • Connecting the button to a database to track Likes
  • Best practices for UX and placement

Follow along as we break down the process step-by-step. By the end, you will have the knowledge to add working Like buttons to your own projects to engage users and collect meaningful data.

Technical Requirements

Before we start coding, let’s outline the key technical pieces needed to make a fully functional Like button:

  • HTML – To display the Like button on the page
  • CSS – To style the button’s appearance
  • JavaScript – To add interactivity and send data to the server
  • Server-side code – To process and record Likes to a database
  • Database – To store Like data for each user and piece of content

Optionally, the button can also:

  • Display a Like count
  • Change styles based on Like status
  • Require user login to Like

We will incorporate all of these elements into our code walkthrough.

Front-End Code

Let’s start by coding the visual Like button that users will click.

HTML

The HTML will contain a clickable

<button class="like-btn" data-content="123" data-user="456">
  <i class="fa fa-thumbs-up"></i>
  <span class="like-count">100</span>
</button>

Key things to notice:

  • The data-content and data-user attributes allow us to pass custom data needed for processing the Like
  • Font Awesome provides the thumb icon SVG with the fa fa-thumbs-up classes
  • The like-count span will display the current Like count, updated dynamically

CSS

The button can be styled with CSS:

.like-btn {
  border: none;
  background: none;
  outline: none;
  cursor: pointer;
}

.fa-thumbs-up {
  color: #999;
}

.like-count {
  margin-left: 5px;
  font-size: 14px;
}

This keeps the button clean with only the essential icon and count visible. The cursor: pointer makes the button clickable.

JavaScript

Next we’ll add JavaScript logic to handle the click event:

// Get button element
const likeBtn = document.querySelector('.like-btn');

// Click event handler
likeBtn.addEventListener('click', function() {

  // Current count
  let currentCount = this.querySelector('.like-count').innerText;
  
  // Send AJAX request to server
  sendLike(this.dataset.content, this.dataset.user);

  // Update count display
  this.querySelector('.like-count').innerText = ++currentCount;

});

// AJAX request function
function sendLike(contentId, userId) {
  
  const data = {content_id: contentId, user_id: userId};
  
  fetch('/like', {
    method: 'POST', 
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  })
  .then(response => {
    console.log('Like sent', response);
  })
  .catch(error => {
    console.log('Error:', error);
  });
}

Here’s what’s happening on click:

  1. Get the current Like count from the span
  2. Call the sendLike function, passing the content and user IDs
  3. Increment the count locally and update the display
  4. The AJAX call sends data to the server /like endpoint
  5. The server response is logged, errors handled

This covers the client-side logic needed to capture the Like and update the front-end. Next we’ll move on to the server implementation.

Server-Side Code

When the front-end JavaScript makes an AJAX request to the /like endpoint, we need server code to receive and process it. This will:

  • Get the content ID and user ID from the request
  • Validate that the user has permission to Like
  • Insert or update the Like in the database
  • Return a response to the client

Let’s see an example using PHP and MySQL:

<?php

// Get data from AJAX request 
$content_id = $_POST['content_id'];
$user_id = $_POST['user_id'];

// Check if user is logged in
if(isset($user_id)) {

  // Connect to DB
  $db = new mysqli('localhost', 'username', 'password', 'dbname');

  // Check if user already Liked
  $sql = "SELECT * FROM likes WHERE content_id=$content_id AND user_id=$user_id";
  $result = $db->query($sql);

  if($result->num_rows == 0) {  
    // Insert new Like
    $sql = "INSERT INTO likes (content_id, user_id) VALUES ($content_id, $user_id)";
  } else {
    // Update existing Like
    $sql = "UPDATE likes SET timestamp=now() WHERE content_id=$content_id AND user_id=$user_id"; 
  }

  // Run query
  $db->query($sql);

  // Success
  $response = ['status' => 'success'];

} else {
  // Unauthenticated user
  $response = ['status' => 'error'];
}

// Return JSON response
header('Content-Type: application/json'); 
echo json_encode($response);

?>  

This basic script gets the job done server-side by interacting with a MySQL database to upsert the Like.

Database Structure

The database requires just a simple likes table schema to store each Like:

CREATE TABLE likes (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  content_id INT NOT NULL,
  timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Each Like row will contain the ID of the user and content being Liked along with a timestamp.

An index on (user_id, content_id) will optimize lookup speed for what will be a high volume table as Likes accumulate.

Displaying Like Counts

Now that we have the back-end fully functioning to process Likes, let’s circle back to the front-end to dynamically display the count.

There are a couple approaches we can use:

Real-time Updates

We can update the Like count in real-time by firing a function to get the latest count anytime a Like is submitted:

// Update like count after clicking
function updateLikeCount() {

  const contentId = this.dataset.content;

  // Send GET request 
  fetch(`/likes/count?contentId=${contentId}`)
    .then(response => response.json())
    .then(data => {
      this.querySelector('.like-count').innerText = data.count; 
    })
    .catch(error => {
      console.log('Error:', error);
    });

}

// Call on click
likeBtn.addEventListener('click', function() {

  // Existing click handler

  updateLikeCount();

});

The /likes/count endpoint would query the database and return the total Likes for that content.

Periodic Updates

For performance, we can also update counts on an interval like every 30 seconds:

// Update counts 
setInterval(function() {

  // Query class for all buttons 
  const likeBtns = document.querySelectorAll('.like-btn');

  // Loop through buttons
  likeBtns.forEach(function(btn) {

    const contentId = btn.dataset.content;

    // GET request to endpoint
    fetch(`/likes/count?contentId=${contentId`)
      .then(response => response.json())
      .then(data => {
        btn.querySelector('.like-count').innerText = data.count; 
      })
      .catch(error => {
        console.log('Error:', error);  
      });

  });
  
}, 30000); // 30 seconds

This allows the count to stay updated across the site but reduces the number of requests needed.

Customizing Button Styles

We can enhance the user experience by customizing the button styles based on Like status:

  • Not Liked – Gray thumb icon, black count
  • Liked – Blue thumb icon, white count
.like-btn {

  &.not-liked {
    .fa-thumbs-up {
      color: #333;  
    }
    
    .like-count {
      color: #000;  
    }
  }

  &.liked {
    .fa-thumbs-up {
      color: #58acf4;
    }
    
    .like-count {
      color: #fff;
    } 
  }

}

Then toggle these classes in JavaScript by checking if the user has liked:

// Check on page load
checkLikeStatus();

function checkLikeStatus() {

  const contentId = likeBtn.dataset.content;
  const userId = likeBtn.dataset.user;

  // Request to /liked endpoint 
  fetch(`/liked?contentId=${contentId}&userId=${userId}`)
    .then(response => response.json()) 
    .then(data => {
      if(data.liked) {
        likeBtn.classList.add('liked');
      } else {
        likeBtn.classList.remove('liked');  
      }
    });

}

Where the /liked endpoint queries the database to see if a Like exists.

This personalized touch improves the experience and visual feedback for the user.

Requiring Login

For many sites, you’ll want to tie Likes to registered user accounts to prevent duplicate clicks and spam.

Some options for integrating authentication:

  • Check for user login on page load and hide/disable button if not logged in
  • Open pop-up login prompt when unauthenticated user tries to Like
  • Require JWT auth token to be passed with AJAX request
  • Redirect to login page as fallback if unauthenticated

Here is an example flow with user ID check on click:

// Click handler
likeBtn.addEventListener('click', function() {

  // Check for user ID
  if(!this.dataset.user) {
    // Open login modal
  } else {
   // Existing handler  
  }

});

And server-side with a JWT token:

// PHP endpoint

// Get token from request header
$token = $_SERVER['HTTP_AUTHORIZATION']; 

// Validate JWT 
if(verifyToken($token)) {
  // Process like
} else {
  // Return error
}

Requiring authentication ensures legitimate Likes and enables analytics on how content performs among logged-in user segments.

Placement and UX Tips

Like buttons are versatile components that can be placed in different locations to drive engagement:

  • Below content – Most common placement for blog posts, videos, etc.
  • Sidebar – Could stack multiple Like buttons in a fixed sidebar
  • Inside content – Useful for longform articles with breaks
  • Floating button – Fixed to side or corner, always accessible

Some best practices for UX:

  • Make the button large enough to tap or click easily on all device sizes
  • Use buttons sparingly to avoid cluttering the interface
  • Animate feedback after clicking such as growing the thumb icon
  • Clearly label the button for users (“Like”, “Recommend”, etc)

Experiment with different placements and style options to determine optimal configurations for your site goals and audiences. Analyze performance over time and iterate to drive more Likes.

Conclusion

That covers everything you need to know to build a custom Like button for your web project. With the front-end UI, back-end logic and database structured properly, you can start collecting meaningful engagement data from users today.

Some key takeaways:

  • HTML, CSS and JavaScript handle the visual button and click logic
  • A server-side language processes and records Likes to a database
  • The database stores user, content and timestamp for each Like
  • Display the Like count in real-time or periodically fetch updated totals
  • Personalize the experience by showing Like status
  • Support authenticated users only if needed

Like buttons are versatile web components that will continue to evolve. Consider enhancing yours with animations or integrating with external APIs to unlock new features. The possibilities are endless!