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

  1. When the link is clicked the vote() function is called with the anchor (<a>) element passed as this
  2. The id, up_11659026, is split at the underscore and the parts passed to an array, v
  3. A new var, item, is given the value at v[1], in this case 11659026
  4. Two calls are made to the hide() function, one with the value up_11659026, and one with the value down_11659026
  5. The hide() function looks for an element with the passed id, if it finds it, the visibility of the element is set to hidden
  6. A var is created, ping, and is an instance of JavaScript's Image object.
  7. By setting the src of ping to the href of the clicked element, the URL is called (in this case a vote is cast by the back-end)
  8. Nothing is returned or rendered as it's unnecessary.
  9. We return false to stop the URL being followed by the browser
  10. If JavaScript is turned off in the browser, the URL is followed when clicked and the same outcome occurs.