Neat Vanilla JS on HackerNews
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.
onclick is never called but the vote is still cast.
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.
How does it work
- When the link is clicked the
vote()function is called with the anchor
(<a>)element passed as
- The id,
up_11659026, is split at the underscore and the parts passed to an array,
- A new var,
item, is given the value at
v, in this case
- Two calls are made to the
hide()function, one with the value
up_11659026, and one with the value
hide()function looks for an element with the passed
id, if it finds it, the visibility of the element is set to
- A var is created,
- By setting the
hrefof 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.
return falseto stop the URL being followed by the browser