Saturday, March 3, 2012 Creating a 'Like' button with jQuery
Here is an example of how to create a simple 'Like' button using jQuery. When the 'Like' button for a record is clicked the number of likes will increment by 1 and the list will be resorted to ensure the most popular records appear first.
When generating the initial page you'll need to ensure the records are sorted by the number of likes in descending order (i.e. the most popular records first).
Firstly, here is our list of records. The important thing to note here is that the ID for each record DIV has the record's database primary key appended to it. We'll use this later for our Ajax request.
Now comes the jQuery. I have added some inline comments to explain what is happening.
And that's it!
Tags
Comments
Monday, March 5, 2012 Gary Fenton
It's good to get visitors to interact by "liking" something, but ordering records based on the number of likes can really distort the popularity ratings and ensure that new comments, possibly some excellent ones, remain at the bottom of the list without being read.
Suppose after a new article is published there are 10 comments and the first few visitors "like" records 1 and 3 and 5. Those records are now the first 3 on the page. More visitors come and half only read the first few comments on the page. They "like" them, so the rating for those comments increases further. This goes on and on so all new comments are placed at the end of a long list or on the last page (if paged) and are hardly read or liked because the first dozen comments were read and liked first and therefore snowballed. I'm not sure if I've explained this well but you only need to look at various busy websites that work like this and you'll see.
I think comments should be ordered by date descending by default (which is the fairest way to give every comment some "air time" with an optional button to reorder by popularity.
Monday, March 5, 2012 Simon Bingham
Hi Gary. Yes, you make a good point. I think it's best to sort by date first and have the option to sort by popularity as a secondary option.
Monday, March 5, 2012 Fadi El-Eter
Hi Simon,
Your code has a little flaw - you can click on the like button as many times and the count will increase with every time you click on the link. A small condition will address this problem.
Monday, March 5, 2012 Simon Bingham
Hi Fadi. My code above does include something to deal with that, but I commented it out in the example so it's easier to see how the sorting works.
Friday, November 16, 2012 Jace Warren
This is an awesome tutorial. However, I have been racking my brain trying to figure out how to allow users to unlike the button. When I say unlike I mean they click the button again and the count goes down one instead of plus one.
How would you add that functionality?
