Custom Like Button

Create your own custom like button.

Code Level

Intermediate

Published

 

Example Description

In this example we create a custom like button.

Example Code

How We Built It

Collections

For this example we use the database collections automatically added to your site when you have a blog and add another one of our own (If you don’t see these collections, refresh your page):

  • Blog/Posts collection (automatic): Contains information about your individual blog posts

  • Blog/Categories collection (automatic): Contains information about your blog categories

  • Post Likes Data collection (custom): Contains the number of likes per post per unique user

    • Note: To simplify this example we set the permission for adding and removing items to ‘anyone’. It's better practice not to set these permissions on the database level and instead handle your data calls in the backend using suppressAuth.

 

Page Elements

In our site we added the following page elements to the Post page:

 

  • “Default” Icon Button (likeButtonDefault): Represent the like button when it is not clicked, regular state and hover states are managed in the button UI settings

  • “Active” Icon Button (likeButtonActive): Represents the like button after being clicked, all button states are the same

  • One overlayed Image for the click animation (likeButtonFocus)

 

Code

  • Create an object for the various likeButton states that will be used

  • Use the getPost() method to get the current page post data and save its ID in a global variable.

  • Query the Post Like Data collection using the currentPostId for the number of likes the current post has 

  • Check the current state of the like button using the .some() method to check if the current user ID matches any item in the Post Like Data collection.

  • Create a function that will handle the state of the like button by showing and hiding the relevant button based on the given button state

  • To add a like, insert it into the Post Like Data collection with the userId

  • To remove a like query it from the Post Like Data collection using the currentPostId and then remove it from the collection using the userId

  • To prevent duplicate likes, add data.js in the backend section of your site and create a beforeInsert function that checks if the item is already present in the collection. You can learn more about preventing duplicate items in the database in this example here

APIs We Used

Related Articles

Related Examples

Add to Cart Gallery

Let customers to add products to their cart

INTERMEDIATE

Hide and Show Elements

Hide and show elements in response to user interactions

BEGGINER

Hide and Show Elements

Hide and show elements in response to user interactions

BEGGINER