A Slightly Better reddit Upvote/Downvote Widget (button)
3 minutes read | 479 words by Ruben BerenguelA few days ago I found myself with a problem. I wanted a reddit button in one of our websites, and our technical guy wanted it to be asynchronous. After a little poking around and deciding that reddit doesn’t offer asynchronous buttons, I rolled my poor man’s version: wrap it in a $(document).ready() It’s not asynchronous, but at least it won’t block page loading.
Both happy, we deployed and I tested. Worked well, no problem. Well, actually, yes. A problem shared by all reddit buttons, one that was very troublesome here in mostlymaths (back when I had a share on reddit button just beside the post title.)
When setting up the button you select the target reddit you’d rather have your users send your content. In a page about Apple stuff, it would be r/apple. The problem is though that your users are free and can do whatever they want. So they go and submit to r/technology. Fine, r/technology is cool enough, lots of readers. Trouble is, when a user arrives from r/technology to your blog, after clicking on the link… He will see your widget with an ugly submit text, and no upvotes or downvotes:
even though your post has quite a few votes already in r/technology. The trouble comes from setting the target subreddit beforehand: if the url is not in this subreddit, reddit looks nowhere else. Of course, you’d rather have:
with the real counter. After all, this means making the experience completely seamless:
- Reddit user sees a cool link to your content in r/whatever. Clicks
- Lands on your page
- Upvotes (or downvotes)
instead of
- Reddit user sees a cool link to your content in r/whatever. Clicks
- Lands on the page
- Tries to upvote, needs to submit instead
- Is forced to submit to r/whatever, gives up (or not)
An easy way to solve this problem is to check the referring URL. If it matches a subreddit, we can set the target of our widget to that subreddit instead of the default one. All reddit readers happy!
There’s another issue, though: users not arriving from reddit.
A random user landing in your awesome post, which has a bazillion points in r/whatever likes your content, and wants to upvote it. But, alas! He sees the dreaded submit button, because our default is r/apple. Or worse, sees 0 (or even a negative number!) because it has been downvoted in our target subreddit.
This can also be solved. Reddit offers a clear-cut json API, allowing jsonp callbacks. This means that we can write a small piece of javascript that will check whether our post has been submitted to another reddit AND change the target to that one! All reddit users happy!
Below you can find the code. Fork it, use it, whatever. Be happy. If something breaks or doesn’t work as expected it’s not my fault: use cases may vary.