8 ms·
The Single Piece of JavaScript on HN
- cypherpunks01 11y agofunction 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 11y agoWhat'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 11y agoFor 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.
- gordonzhu 11y agoYES! totally agree For a subset of us, framework authors, open source contributors, etc. It's very useful to keep up to date on the latest trends. For example, the Angular team has borrowed techniques from React. It helps for them to keep up with things. For people like me though, let's be honest. I don't need to do the latest thing.
- pixel67 11y agoFunny you said that, I was looking into ng2 and they've borrowed a few things from the React community. It's all good, I'm glad to see that "framework A is better than framework B" mentality die away and everyone just uses the right tool for the right job.
- percept 11y agoThe problem (from my perspective) is that the job market follows. It's good at that--always following.
- zeemonkee3 11y agoAnd so we use React in our project (even if it makes no sense to) because then we can put it in our resume. And thereby contribute to the problem.
- xupybd 11y agoTotally agree. One problem I find arises from this is that there are no boring workhorses. Time and time again I need boring crud screens, for the admin side of applications, but there is no easy default to choose. ExtJS tends to do the trick, but it's not cheap.
- vmorgulis 11y ago> Time and time again I need boring crud screens, for the admin side of applications, but there is no easy default to choose. crud is often a feature of frameworks. crud should be an external tool like documention tools (doxygen...).
- zappo2938 11y agoThis week's JavaScript flavor special is vanilla.
- catshirt 11y agomaintaining software is a real thing. for the majority of cases i've seen, these arguments are to save developers time and the company money. my gut & feelies tell me there is truth to "it doesn't really matter what technologies you use" but my brain and experience tell me that is objectively false.
- nostrademons 11y agoThe reason "it doesn't matter what technologies you use" is because successful software gets rewritten multiple times anyway. It matters a lot eventually, but having an "eventually" to worry about is a nice problem to have. (There's also a big perspective difference between being an entrepreneur writing initial code for a project vs. an engineer hired to maintain & grow that code. Code quality, architecture, and technology choice matters a lot to an engineer who will be working with it directly. It matters a lot less to a business that can swap out engineers until they find ones who enjoy working on that codebase. The fact that you even have money to hire engineers usually indicates that the existing code is getting the job done. The business only gets screwed when the code quality is so bad that nobody can make sense of it, and the environment changes in a way that requires modifications.)
- catshirt 11y agobut, there are many instances where software would not get rewritten with proper technical foresight in the first place. i take your point none the less- there are contexts where it doesn't matter.
- daxfohl 11y agoWould love to see "Enterprise HN" with Node and React and Redux (with server-side rendering), and how it compares (whether horribly or awesomely).
- sundarurfriend 11y ago> 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 11y ago> 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...
- Ezhik 11y agoWell, there's Designer News...
- kriro 11y agoThat's already a pretty "modern" enterprise stack. I'd expect enterprise HN to run on Java EE (with an Oracle DB of course) :D
- em500 11y agoHave you seen hn.algolia.com?
- staticelf 11y agohttps://vuejs.github.io/vue-hackernews/#!/news/1 https://vuejs.github.io/vue-hackernews/#!/news/1 Not exactly any of these technologies, but it is using more javascript at least. I think the example is pretty awesome actually.
- welder 11y ago+1 times infinity
- deleted 11y ago[deleted]
- ignoramous 11y agoThe img.src trick is used by google-analytics to log metrics cross-domain as well. Pretty neat trick. Another thing to note is the "RESTful" nature of the links embed in the page. I guess its some form of HMAC with SHA1 + Nonce that authenticates requests for the server. It differs for every href. Elegant. auth=311110b7ef0f268cafa8616afcbfcec8d977111e
- deleted 11y ago[deleted]
- nathancahill 11y agoLol. For hiding a voting arrow after it's clicked. Yes, you're right. You don't need any of that stuff. But if you were to write an entire app in the style of those two functions, things would fall apart. That's not even a hypothetical, it's been proven over and over again that it doesn't work. How is everyone agreeing with you? Is there that much JS fatigue that we're looking at the equivalent of a horse-drawn carriage, and saying wow, I wish things were as simple as they were back then?
- snowwrestler 11y ago> Is there that much JS fatigue that we're looking at the equivalent of a horse-drawn carriage, and saying wow, I wish things were as simple as they were back then? Make Javascript Great Again! (TM)
- kylemathews 11y ago>horse-drawn carriage That code is more the equivalent of a digging stick. React is used to build horse-drawn carriages. I'm eagerly awaiting the JS framework that'll let me build cars.
- BillinghamJ 11y agoI think the point is that there's actually little wrong with using standard HTML forms and hyperlinks most of the time. There is an increasing trend to move the whole website to the client side to be handled entirely by the JavaScript as a single actual page. Personally I find most websites work better with a simple round trip to the server to fetch more HTML. So actually building an entire system in this style isn't out of the realms of possibility at all - you just only write JavaScript for the cases where there is a real legitimate benefit to doing so.
- joshstrange 11y ago> Personally I find most websites work better with a simple round trip to the server to fetch more HTML. > you just only write JavaScript for the cases where there is a real legitimate benefit to doing so The snippet above only works because HN is so simple, normally the rule of thumb is if you are going to use JS to change the DOM at all then you need to render it in the first place using JS or else you are double-implementing the render logic and you open yourself up to changing one implementation and not the other. For hiding arrows sure this works but 99.999% of the time it's a very bad idea to use JS to change the dom to a state that the server would otherwise render on a page reload. You may feel that a round trip works better but that's not what users expect or will tolerate most of the time. That kind of thinking feels very close to people who think CRUD is all you need to build an app. Sure you can build an app with just that but thinks break down very quickly.
- davidw 11y agoThat was a lot easier than watching an entire video.
- vmorgulis 11y agoWith closure compiler: function hide(a){if(a=document.getElementById(a))a.style.visibility="hidden"}function vote(a){var b=a.id.split(/_/)[1];hide("up_"+b);hide("down_"+b);(new Image).src=a.href;return!1}; v and item are merged. http://closure-compiler.appspot.com/home#code%3D%252F%252F%2520%253D%253DClosureCompiler%253D%253D%250A%252F%252F%2520%2540output_file_name%2520default.js%250A%252F%252F%2520%2540compilation_level%2520SIMPLE_OPTIMIZATIONS%250A%252F%252F%2520%253D%253D%252FClosureCompiler%253D%253D%250A%250Afunction%2520hide%28id%29%2520%257B%250A%2520%2520%2520%2520var%2520el%2520%253D%2520document.getElementById%28id%29%253B%250A%2520%2520%2520%2520if%2520%28el%29%2520%257B%2520el.style.visibility%2520%253D%2520%27hidden%27%253B%2520%257D%250A%2520%2520%257D%250A%2520%2520function%2520vote%28node%29%2520%257B%250A%2520%2520%2520%2520var%2520v%2520%253D%2520node.id.split%28%252F_%252F%29%253B%250A%2520%2520%2520%2520var%2520item%2520%253D%2520v%255B1%255D%253B%250A%2520%2520%2520%2520hide%28%27up_%27%2520%2520%2520%252B%2520item%29%253B%250A%2520%2520%2520%2520hide%28%27down_%27%2520%252B%2520item%29%253B%250A%2520%2520%2520%2520var%2520ping%2520%253D%2520new%2520Image%28%29%253B%250A%2520%2520%2520%2520ping.src%2520%253D%2520node.href%253B%250A%2520%2520%2520%2520return%2520false%253B%250A%2520%2520%257D http://closure-compiler.appspot.com/home#code%3D%252F%252F%2... Original Size: 212 bytes gzipped (318 bytes uncompressed) Compiled Size: 164 bytes gzipped (182 bytes uncompressed)
- seanalltogether 11y agoIf 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.
- dikaiosune 11y agohttps://chrome.google.com/webstore/detail/hacker-news-collapse/pdlifinplmfmoeppfooipommbdljhdmp?utm_source=chrome-app-launcher-info-dialog https://chrome.google.com/webstore/detail/hacker-news-collap... I don't know about other browsers, but this works OK on Chrome.
- deleted 11y ago[deleted]
- lurker2015 11y agoIs there anything like Reddit Enhancement Suite for HN? Any recommendations out there?
- meesles 11y agohttps://chrome.google.com/webstore/detail/hackernew/lgoghlndihpmbbgmbpjohilcphbfhddd?utm_source=chrome-app-launcher-info-dialog https://chrome.google.com/webstore/detail/hackernew/lgoghlnd...
- thieving_magpie 11y agoYes, 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-enhancement-s/bappiabcodbpphnojdiaddhnilfnjmpm?utm_source=chrome-app-launcher-info-dialog https://chrome.google.com/webstore/detail/hacker-news-enhanc...
- deleted 11y ago[deleted]
- deleted 11y ago[deleted]
- sillysaurus3 11y agoLittle-known fact? Man, this place really got big. :)
- krapp 11y agoProbably not "little known" so much as "little cared about."
- meesles 11y agoNot much to say, really. Just some simple code. What I'm curious is if someone can reiimplement this without and javascript.
- krapp 11y agoWithout javascript you would just keep track of which comments the logged-in user voted on in the requested thread and not render those buttons.
- ggreer 11y agoHN has to do that anyway. The hide() and vote() functions only run on click. If you refresh the page, you'll see the response lacks anchor tags for comments/posts you've voted on. Those tags are replaced with a spacer image.
- Normal_gaussian 11y agoWell 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.
- mchahn 11y agoSo without JS enabled you can't vote?
- jey 11y agoNo, you just can't vote without triggering a page navigation. (It's probably HTTP POST with redirect.)
- z3t4 11y agoYou can vote without JavaScript! This is the old-school way; you first make your site work without JavaScript, then add JS to enhance it.
- gordonzhu 11y agoWithout JS, return false from the vote function wouldn't happen, so I guess clicking upvote would follow node.href, which would send the vote to the server. It would work anyway, there would just be a redirect that would trigger a page refresh. Pretty cool. Just tried it out and confirmed.
- mchahn 11y agoI'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 11y agoThe downvotes are how you know.
- kentor 11y agoHe exposed his auth id
- gordonzhu 11y agoThe video mentions this was a dummy account created just for this video.
- z3t4 11y agoSeeing 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 11y agoThis has already been exploited at least once: https://news.ycombinator.com/item?id=639976 https://news.ycombinator.com/item?id=639976
- wrigby 11y agoWhen you're not logged in, the `onclick` attributes aren't present in the anchor tags.
- gordonzhu 11y agoWhen you try to vote it will ask you to log in.
- zbruhnke 11y agoand yes Author is right ... you need 500+ Karma to downvote
- andrelaszlo 11y agoCan you even downvote root items, i.e. topics? I have 500+, and I can't.
- amelius 11y agoNow if only I could convince my UX designer that websites without much JavaScript are cool.
- pmlnr 11y agoShow 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.
- marknadal 11y agoWhy was this post taken off the homepage? EDIT: Now it has been restored, odd.
- mwcampbell 11y agoThe 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.
- olavgg 11y agoActually, another way to do this is to create a form with the POST method that respond with status 204(which will not refresh the page). There is still no need to involve the XHR. I still think this solution is neat though.
- raldi 11y ago"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/
- lifthrasiir 11y agoIt is possible to do so but may not be desirable anyway. It is completely possible to wire a fork bomb to the safe methods; you probably don't want to enable the bomb via crawler however.
- cname 11y agoI don't think that's referring to a case like this. I'd also argue that voting _does_, slightly, change the representation.
- raldi 11y agoOnly in the same way that watching a YouTube video changes the view count. Do you believe that's an invalid use of GET?
- podgib 11y ago
- iamleppert 11y agoWhy 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 11y agobinary is next...
- chei0aiV 11y agohttps://en.wikipedia.org/wiki/WebAssembly https://en.wikipedia.org/wiki/WebAssembly
- tim333 11y agoThe funny thing is that it's always been possible to write a bit of plain javascript but you don't seem to get much respect for that compared with the buzzword stuff.
- nathancahill 11y agoThe funny thing is, it's actually those things (along with Typescript, Flux, etc) that allows us to write readable and maintainable JS that doesn't devolve into spaghetti after a year.
- razwall 11y agoCSRF anyone?
- fabulist 11y agoTry it. You'll find HN an interesting target.
- smadge 11y agoA 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.
- sotojuan 11y agoBut they need it to keep their job :p
- DonHopkins 11y agoBut they'd have more hours to bill if they bothered to make their web pages work with JavaScript disabled!
- microcolonel 11y agoFor me it doesn't bother reloading; but it shows up when I reload.
- mikekchar 11y agoThis is true, however javascript is a tool that can be useful if you are building something that provides an interactive experience for the user. In such a scenario, I have to write code somewhere to provide the experience. If I am writing it on the server side I run into several issues. It uses server resources. For example, let's say the user is looking at a large dataset. They want to sort/search/filter that dataset. Given that they already have the data in their client, it often makes sense to use their resources to sort/search/filter the data. This lightens the load on the server. User actions suffer from latency talking to the server. Again, if the user already has all the data that they want, not talking to the server can often result in a better user experience. Imagine something like an incremental search. Such a thing might even be impossible to implement server side due to latency issues. Implementing client side functionality in the server can add to software complexity. Things like keeping track of user state can be handled much more cleanly on the client side. Very often it makes tremendous sense not to make a "web page" for something that needs a lot of user interaction. Instead you want a stand alone application that gets data (without presentation) from a server. Writing your application in javascript, running it in a browser, using HTML as a presentation layer and using HTTP as your communication protocol is not a stupid way of implementing such an application (and I say this having written these kinds of applications with a variety of different technologies). If you are writing a web page that is intended to simply present data, then Javascript may very well be unnecessary. For me, though, this does not come anywhere close to 90% of my goals.
- mdavidn 11y agoUsing 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 11y agoYes, 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 11y agoReminds 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...
- hayksaakian 11y agothanks, i learned how to use the chrome JS debugger today
- lucb1e 11y agoWhat 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.
- cpg 11y agoOh 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 11y ago[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-ennoblement-facilitation.html http://angularjs.blogspot.com/2016/02/angular-150-ennoblemen... 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.
- Illniyar 11y agoI 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.
- jmiserez 11y ago>responsiveness to mobile. Please no. I like being able to zoom in or out, and too often "responsive" means no zoom and either huge or miniscule text.
- mynewtb 11y agoOpera lets you override that!
- paulryanrogers 11y agoThis. Their text size and reflow are all that I miss from Opera Mobile.
- cname 11y ago"Responsive" doesn't mean those things. Just because some sites fail to design a decent mobile experience, doesn't mean HN (or you or anyone else) can't.
- jmiserez 11y agoI remember some of the early HTC Android phones had text reflow enabled by default. That was almost always good enough and it would be "responsive", but for some reason mobile browsers don't seem to offer it anymore.
- 11y ago
- gedrap 11y agoIs 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 11y agoNot just you. I don't see why this warrants a 12 minute video.
- st3v3ndungan 11y agoI'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 11y agoThanks 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.
- rawTruthHurts 11y agoWell, if that's all you need, that's all you need.
- plugnburn 11y agoSo 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.
- teddyh 11y agoI 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#AppendixA https://www.gnu.org/philosophy/javascript-trap.html#Appendix...
- hjek 11y agoWouldn'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)
- pmlnr 11y agoOldschool, smart, mini javascript as progressive enhancement. Everyone should learn the basics before frameworks. ( Also: http://vanilla-js.com/ http://vanilla-js.com/ )