Neat Vanilla JS on HackerNews
I recently saw this video by Gordon Zhu highlighting the small but extraodinarily clever JavaScript on the Hacker News website.
I felt it would help me if I simplified it and broke down the steps for future reference. I'm using Paul Buchheit's code verbatim, I hope he doesn't mind, full credit to him.
What does this achieve?
This code is called when an anchor (a link) is clicked to vote up an item on Hacker News. It casts the vote and hides the vote up link so it can't be clicked again.
HTML
The markup for this is REALLY simple. It's a perfect example of progressive enhancement. The full URL is present in the HREF so if JavaScript is turned off the onclick
is never called but the vote is still cast.
<a id="up_11659026" href="vote?for=11659026&dir=up" onclick="return vote(this);">Vote Up</a>
JavaScript
No JQuery here! This is concise and elegant vanilla JS. The only JS on the site is following two functions, with the latter calling the former.
function hide(id){
var el = document.getElementById(id);
if (el) { el.style.visibility = 'hidden'; }
}
function vote(node){
var v = node.id.split(/_/);
var item = v[1];
hide('up_' + item);
hide('down_' + item);
var ping = new Image();
ping.src = node.href;
return false;
}
How does it work
- When the link is clicked the
vote()
function is called with the anchor(<a>)
element passed asthis
- The id,
up_11659026
, is split at the underscore and the parts passed to an array,v
- A new var,
item
, is given the value atv[1]
, in this case11659026
- Two calls are made to the
hide()
function, one with the valueup_11659026
, and one with the valuedown_11659026
- The
hide()
function looks for an element with the passedid
, if it finds it, the visibility of the element is set tohidden
- A var is created,
ping
, and is an instance of JavaScript'sImage
object. - By setting the
src
ofping
to thehref
of the clicked element, the URL is called (in this case a vote is cast by the back-end) - Nothing is returned or rendered as it's unnecessary.
- We
return false
to stop the URL being followed by the browser - If JavaScript is turned off in the browser, the URL is followed when clicked and the same outcome occurs.