
The Single Piece of JavaScript on HN - qasar
http://blog.watchandcode.com/2016/03/17/the-single-piece-of-javascript-on-hacker-news/
======
cypherpunks01

      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;
      }

~~~
gordonzhu
What's most fascinating to me about this isn't the simplicity, it's that this
code has lived for so long with almost no changes.

It's a great counter-example to all the recent articles about JavaScript
fatigue. It's good for us to see real examples of sites that aren't caught up
in the framework of the week hype.

At the end of the day we're trying to make stuff that works. ES5 vs ES6, React
vs Angular vs. Ember vs. Aurelia, Angular 1 vs Angular 2, even server rendered
templates vs. single page apps - it all matters a lot less than we think.

~~~
aaronbrethorst
For the majority of cases that I've seen, these arguments are simply excuses
to avoid doing real work. It's way more fun to decide whether your amazingly
awesome Unicorn startup is going to use React or Angular, or Express vs.
Rails, or whatever than it is to actually go through the hard work of building
a customer base and making money.

~~~
daxfohl
Would love to see "Enterprise HN" with Node and React and Redux (with server-
side rendering), and how it compares (whether horribly or awesomely).

~~~
sundarurfriend
> and how it compares (whether horribly or awesomely).

Given only the tech stack, it can go either way, depending on whether the
implementor takes the easy, lazy route or actually puts some thought and
hardwork into it. The problem is, as per good old Sturgeon's law, 90% of sites
take the lazy route, and end up with tangled monstrosities that look like
offerings to the Flying Sphaghetti Monster.

(Also, it's interesting how quickly 'cool new tech' can become 'Enterprise'
_shudder_ when it's widely abused and misused.)

~~~
ethbro
_> Also, it's interesting how quickly 'cool new tech' can become 'Enterprise'
shudder when it's widely abused and misused_

Is this the hipster corollary to coding? Sure, Java was cool when only 100
people were using it...

------
Illniyar
I see a lot of comments here about how not having js on the page is a great
thing and lets get back to the old days.

Lets be frank here, HN's UI is not good. At the very least it needs
collapsible comments and responsiveness to mobile.

The fact that HN is a success is despite its bad UI, or maybe because of the
many HN readers out there that fix all the broken stuff on the page.

While js on sites have surely overgrown, and there is a place for minimalism,
I really don't want to go back to the old days where every click reloaded the
page and interactivity was really only done in flash.

~~~
JupiterMoon
HN's design is fantastic - it is totally perfect for its function. Collapsible
comments are a pig to use. HN looks and works great on mobile now (it didn't
used to but they did a redesign in the last few months).

Downvoters do you care to explain why you disagree?

~~~
probably_wrong
> HN looks and works great on mobile now (it didn't used to but they did a
> redesign in the last few months).

For the record, after the redesign the comments looks worse on Windows Phone.
I know, no one gives a damn about WP, but a "proper" mobile redesign would
work on every browser.

~~~
JupiterMoon
Is that the fault of HN or Windows Phone?

~~~
shawabawa3
HN.

Makes me thinkg of that great rant my Linus about breaking userspace by
"fixing" a "bug"

If you break something for a significant portion of your users, even if it's
caused by someone/something else doing something dumb, it's still your fault

~~~
JupiterMoon
In the case of the web we have standards which describe correct behaviour. Is
HN not following them?

------
gedrap
Is it just me, or it sounds... cult-ish / overly dramatic?

>> it wasn’t obvious to me that Hacker News had any JavaScript at all.

I guess he never votes.

>> I thought it would be weird and complicated, but it turned out to be quite
the opposite. You’ll have to watch the video to see what I mean.

Well, it sends a HTTP request and hides an element. How on earth can it be
complicated? I mean, ok, you can use The Framework Of The Week to do that and
just that. Not everything that is related to HN/YC is some magical rocket
science.

~~~
rohanprabhu
Not just you. I don't see why this warrants a 12 minute video.

~~~
st3v3ndungan
I'll give you one reason. I've never done any front-end stuff before. But
maybe a month ago, I got curious. Perhaps because I read HN everyday.

And if you try to immerse yourself in the front-end world, you get 'yeah,
learn HTML/CSS/JS, BUT, also learn Angular, React, JQuery, et. al...' It's
good to get a reminder that Javascript in and of itself is a capable language.
I'm sure I'm not the only one in this camp.

Maybe it didn't need to be _12_ minutes, and it was certainly more of an 'oh,
interesting' than anything, but I'm glad I took the time to watch it.

~~~
gordonzhu
Thanks for the perspective.

This is why I encourage all developers to take some time to teach new people.
The "everyone knows this obviously" attitude goes away very quickly if you
start doing this.

The aim of the video was to make it accessible to just about everybody. So if
you know this stuff you can watch the first minute and stop the video and get
value out of it. On the other hand, if you're a beginner and you just did
Codecademy, you can watch it through and follow it too.

------
smadge
A few weeks ago I turned off javascript in my browser out of principle and to
see if progressive enhancement was still a thing web developers cared about
(hint: it's not). I was pleased that HN worked fine, and the only annoying
thing was that voting caused a page reload. It's nice to see this get the
attention it deserves!

Developers! You probably don't need javascript to achieve 90% of your goals.
It will just slow your page load speeds.

~~~
plugnburn
The next major update in all browsers absolutely must be this: inability to
turn off JS. Because no one in a sane state would EVER do this now.

Why not a checkbox to turn off HTML? It would be just as "useful"...

I do need JS to achieve all my goals that can be achieved with JS. For those
things that can be achieved without JS but often mistakenly involve it
(hamburger menus, animations etc), I use plain markup and CSS3. But I'm not
going to ruin the UX on mobiles, where in developing countries traffic still
matters, just for some paranoid freaks' sake.

~~~
smadge
Your site will be much more usable in developing countries with low spec
mobile devices and high latency, low bandwidth networks if you design it to
function first without JavaScript. You will reduce page weight, and client
side CPU usage.

~~~
plugnburn
Client-side CPU usage, as well as page weight, isn't a problem if JS is done
right. Angular-like bloatware certainly ruins all the zen. But that doesn't
mean you should rush to another margin and make everything server-side. Modern
web technologies allow you to keep everything beautiful, smooth AND
lightweight. But in order to achieve that, you'll need to learn more than a
couple of bloatware libs like angular or jquery. In fact, you need to forget
them and start thinking for real. And study, study and once more study MDN
manuals.

Language doesn't make Web slow and bulky. People do.

~~~
smadge
Agreed! Learning the latest and greatest library isn't going to make you a
better developer. I'm not saying client side scripting has no place on the
web, I'm just saying for many purposes its place is overrated, and that basic
functionality can be provided through hypermedia alone.

------
mwcampbell
The HTTP request for voting should be a POST request, not a GET request, since
it changes state. So both the JS hack involving an image and the non-JS
fallback are broken. The JS function should use XHR, and I guess the non-JS
fallback should be a form with an image button, not a link.

~~~
raldi
"However, this is not completely true. It means: it won't change the resource
representation. It is still possible, that safe methods do change things on a
server or resource, but this should not reflect in a different
representation."

[http://restcookbook.com/HTTP%20Methods/idempotency/](http://restcookbook.com/HTTP%20Methods/idempotency/)

~~~
cname
I don't think that's referring to a case like this. I'd also argue that voting
_does_, slightly, change the representation.

~~~
raldi
Only in the same way that watching a YouTube video changes the view count. Do
you believe that's an invalid use of GET?

------
iamleppert
Why isn't this wrapped in a react component and written with ES7 lambda
functions, transpiled from JSX (using babel of course)?

God I hate what has happened to the web these days.

~~~
awqrre
binary is next...

~~~
chei0aiV
[https://en.wikipedia.org/wiki/WebAssembly](https://en.wikipedia.org/wiki/WebAssembly)

------
mdavidn
Using this approach, a badly written prefetch add-on might automatically vote
on everything. Any request that modifies server-side state really should use
POST or PUT (or, at the very least, append a CSRF token in JavaScript).

I eventually find this bug on just about every project. One time a user
complained that all comments would disappear from her posts. Found that an
add-on was prefetching all "delete" links, visible only to her.

~~~
Semiapies
Yes, this is an old problem. It came up with early versions of Rails
scaffolding, which only used GET at the time. There's no excuse for deleting
with GET.

~~~
dividuum
Reminds me of an old story about an internal wiki at a company I once worked.
They tried to add a search feature which initially crawled all pages. Once
that was done, the complete wiki was empty...

------
seanalltogether
If we ever make it around to a second piece of javascript on here, can I
request that it be a collapse comment function? I promise i won't ask for
anything else.

~~~
lurker2015
Is there anything like Reddit Enhancement Suite for HN? Any recommendations
out there?

~~~
thieving_magpie
Yes, aptly named "Hacker News Enhancement Suite". I use it and think it does
fine, mainly just for collapsing comments.

[https://chrome.google.com/webstore/detail/hacker-news-
enhanc...](https://chrome.google.com/webstore/detail/hacker-news-
enhancement-s/bappiabcodbpphnojdiaddhnilfnjmpm?utm_source=chrome-app-launcher-
info-dialog)

------
meesles
Not much to say, really. Just some simple code.

What I'm curious is if someone can reiimplement this without and javascript.

~~~
Normal_gaussian
Well there appear to be two things stopping this:

\- Hiding two elements on the page (one can be hidden with the CSS :visited
selector)

\- Remaining with your position on the page whilst also sending a message to
the server and without opening new windows.

So the only way to do the task is to send a full request to the server which
would return you to the page with the buttons correctly disabled. Extra load
on the server of course, and a bit of an annoying user experience, but doable
- hence why this is the disabled fallback.

~~~
dfabulich
You could render the vote buttons in iframes, so just the iframe would reload.
But you'd have to load N iframes for N vote buttons on page load. Not worth
the performance hit.

~~~
ars
> But you'd have to load N iframes for N vote buttons on page load.

No you don't. Use a FORM with a target of the iframe, make each arrow an
<input type=image name="id#">

One form can cover all the arrows at once. Or you can have a form per set of
arrows. Either way you only need one iframe.

Making it hide is a bit more complicated:

One way is have it hide on focus using visiblity, then set a very long
transition in the CSS rules to unhide.

------
mchahn
So without JS enabled you can't vote?

~~~
mchahn
I'm getting clobbered with downvotes. I need to ask less stupid questions. The
problem is that I don't really have a way to know they are stupid.

~~~
krapp
The downvotes are how you know.

~~~
mchahn
Now I see you are downvoted. I thought your comment was humourous which is
always alright to me.

In My Humble Opinion downvotes are given out a little too easily here (OK, I'm
ready for more downvotes). I hope when I get the downvote ability I will use
it wisely, not that many aren't wise.

~~~
krapp
Downvotes aren't worth worrying about on Hacker News, nor are upvotes. They do
tend to even out in time so that only the really objectionable comments get
downvoted a lot (and eventually flagged) but because pg more or less decided
that there didn't need to be a standard for either, I treat them as worthless.

~~~
mchahn
I take it personally which I know I shouldn't. I think others are the same.
You can tell when people say "Why was I downvoted?!".

Everyone wants peer approval. Also you get the same feeling you get when you
are being denigrated by someone who doesn't have the backbone to come out and
say who they are. I say you get the feeling, not that it is true.

~~~
oldmanjay
Feeling slighted is fine, but it's best to keep the reaction off the site
unless you want more downvotes.

------
z3t4
Seeing the "auth" query. There is a chance that HN was "too clever" about it,
and it might be possible to use other users id to upvote, or upvote many
times, if you can figure out the hash algorithm.

~~~
firloop
This has already been exploited at least once:
[https://news.ycombinator.com/item?id=639976](https://news.ycombinator.com/item?id=639976)

------
amelius
Now if only I could convince my UX designer that websites without much
JavaScript are cool.

~~~
pmlnr
Show them these:
[http://tympanus.net/codrops/category/blueprints/](http://tympanus.net/codrops/category/blueprints/)

A lot of those are either without javascript or with minimal, vanilla js.

------
teddyh
I wish the code had a license. It is easy enough to add a license to inline
Javascript so that it is machine-readable:

[https://www.gnu.org/philosophy/javascript-
trap.html#Appendix...](https://www.gnu.org/philosophy/javascript-
trap.html#AppendixA)

~~~
hjek
Wouldn't this piece of code be classified as "trivial" by the policy in the
link, and therefore not need it?

Anyway, if you download the source and look in the 'copyright' file it says:

"This software is copyright (c) Paul Graham and Robert Morris. Permission to
use it is granted under the Perl Foundations's Artistic License 2.0"

[http://www.arclanguage.org/arc3.1.tar](http://www.arclanguage.org/arc3.1.tar)

(I'd be more worried about the license of the Algolia Search provided on
Hacker News. Way more JS there. It's even using AngularJS)

------
sillysaurus3
Little-known fact? Man, this place really got big. :)

~~~
krapp
Probably not "little known" so much as "little cared about."

------
lucb1e
What I find interesting is that even this little piece could be done in plain
HTML using an iframe for each vote button. The obvious disadvantage is http
requests for each vote button, but even a middle ground could be chosen where
the vote buttons submit to a hidden iframe and just don't disappear without
Javascript. Perhaps even, but I'm not certain, they could be made to disappear
using css' a:visited, loosing zero functionality and having no disadvantages.

------
zbruhnke
and yes Author is right ... you need 500+ Karma to downvote

~~~
andrelaszlo
Can you even downvote root items, i.e. topics? I have 500+, and I can't.

------
cpg
Oh the irony ..

> Want to take your AngularJS skills to the next level? If so, check out our
> flagship product, Angular Course. Through 115 HD videos, you'll learn
> Angular and the latest best practices as you build a fictional startup.

~~~
gordonzhu
[I made the video]

I don't think this is ironic at all. When I mentioned "framework of the week
hype" in my initial comment
([https://news.ycombinator.com/item?id=11308043](https://news.ycombinator.com/item?id=11308043)),
I was thinking specifically about how people are handling the transition from
Angular 1 to 2. I am in no way advocating using plain JavaScript to build your
app. I even mentioned in the video that I rarely work with plain JavaScript.

There's a lot of distraction around Angular 2 for both existing and new
developers, when it's pretty clear to me that Angular 1.9.x will pretty much
look like Angular 2. If you read the release notes, this is very clear. They
said the the primary theme for the 1.5 release was improving the upgrade path
to Angular 2.

[http://angularjs.blogspot.com/2016/02/angular-150-ennoblemen...](http://angularjs.blogspot.com/2016/02/angular-150-ennoblement-
facilitation.html)

What this means is that keeping up with the Angular 1 release cycle will
gradually transition you to Angular 2. But everyone in the community seems to
think this is boring and wants to blow up their apps and go to Angular 2 right
away.

This is the kind of thinking that I wish we'd see less of. Rushing to 2 when
it's still in beta makes no sense from a business perspective. It only makes
sense from a "I like to tinker with the new thing and try new stuff because
it's fun" perspective. Some people will say it's a performance issue (since
Angular 2 is better in that respect), but for the vast majority of apps that
want to upgrade to 2 now, the improvements won't be noticeable.

------
pmlnr
Oldschool, smart, mini javascript as progressive enhancement.

Everyone should learn the basics before frameworks.

( Also: [http://vanilla-js.com/](http://vanilla-js.com/) )

------
wrigby
When you're not logged in, the `onclick` attributes aren't present in the
anchor tags.

~~~
gordonzhu
When you try to vote it will ask you to log in.

------
rawTruthHurts
Well, if that's all you need, that's all you need.

------
kentor
He exposed his auth id

~~~
gordonzhu
The video mentions this was a dummy account created just for this video.

------
hayksaakian
thanks, i learned how to use the chrome JS debugger today

------
razwall
CSRF anyone?

~~~
fabulist
Try it. You'll find HN an interesting target.

------
plugnburn
So yeah, let's all go back to the stone age just because of some purist morons
with JS disabled.

In my honest opinion, the only possibility browser vendors should disable
these days is the possibility to turn JS off.

------
marknadal
Why was this post taken off the homepage? EDIT: Now it has been restored, odd.

