Great resource, I've bookmarked it.<p>You know where vanilla JS still has a legitimate usecase in the era of SPAs? Landing pages.<p>- Mostly static HTML, time to first render is critical, all you want is a little bit of (progressively added) flair<p>- Can be inlined for instant loading/execution, no bundle download (or SSR) necessary<p>- Code has low volume and scope so structure / spaghetti isn't a concern<p>- You can separate it out from the rest of your SPA bundle(s), so shipping changes is completely decoupled from your SPA CI/CD process and can be done as frequently as you like and <i>very</i> quickly
This site is a real gem. Clean, simple, and minus the excessive complexity and obfuscation caused by frameworks. Doing & Learning things in plain JS we can learn fundamentals.
The problem with vanilla JS is not APIs, API is the easy thing. The problem is building proper architecture, so code won't quickly turn into spaghetti. With frameworks like Angular or React, it's much easier, as the general structure is dictated by framework and developer just have to follow good practice. With vanilla JS it's the wild west.
Making decent UI's went from bicycle science to rocket science. VB-classic was easy to learn and easy to use, and you had coordinate control over where most things went on the screen. If your layout engine didn't put it where you had planned, you can just tell the widget to "go right here". You felt in charge of the screen, not some abstract layout layer with an attitude. A manager (person) could draw something on the back of a napkin and you could make it <i>exactly</i> match the napkin because you were in charge of exactly where things went. (Layout engines were optional then.)<p>The newer UI frameworks are round-about and confusing. They make it easy to get 80% of what you want, but that last 20% is bear, requiring long trial-and-error periods, unless you are heavily versed in them. Abstraction is only nice when it does what you want, not when it becomes "abstract art".<p>The price for "responsive" (client-side auto-placement) has been huge. In applications that are primarily for office desktops, their advantage is lost. Mouse and PC's is still where most real work is done. Instead we are using things like Bootstrap, designed for social networks, not real work. Glamour won over logic.<p>It's great job security for UI experts, but expensive for organizations because they need stack specialists whereby before a one-man-band (or 2) could make useful apps for less than half the cost and time without having to spend years with UI-Yoda to master some screwy layout engine.<p>Something is wrong.
> This approach isn't recommended because we can only attach one handler for each event.<p>Except when you <i>do</i> want that behavior. E.g., you only want to set one listener and have a stream of data coming in that can trigger various attachments/detachments to the same element(s) over and over.<p>With the ancient "on" methods you get a single method that you can replace at will. Unbinding happens automatically. For example, you can keep assigning to an anonymous function till your heart's content and there will only ever be one callback in that slot attached as the author states.<p>With the new, "recommended" methods you must manually track the state and unbind old callbacks. For example, you would have leaky behavior if you kept assigning anonymous functions with addEventListener. And you can't easily hack your way out of the state problem because the DOM doesn't give you a way to fetch the current number of listeners, reset them to default or really know anything about them.<p>So the recommended behavior does not include in its design the ability to achieve the useful old behavior.<p>But at least DOM does have a convenience method to toggle class that will save a good 10 seconds per year of dev time.
Coincidentally, I just commented yesterday about an interview experience I had about the DOM. I did not expect it to be so highly upvoted. <a href="https://news.ycombinator.com/item?id=22740897" rel="nofollow">https://news.ycombinator.com/item?id=22740897</a>
I recently built a small side project in vanilla js for fun. I just didn't want to break out webpack and waste an hour getting it set up.<p>I got pretty far, did all the design. I wanted to run a client side simulation in javascript though, and found I needed to host a local server as chrome refused to read modules from a file due to CORS permissions (running chrome with the usual arguments didn't fix it).<p>At this point, since I needed an outside piece of software to run things anyway, I figured I might as well switch to webpack dev-server and get the whole modern frontend ecosystem. I then quickly started replacing my home grown dom syncing with vuejs, and snowballed from there.<p>I definitely learned a couple things, so time well spent, but I'm also going straight to webpack next time. I know it'll only take a few hours before I start hitting the limits of what vanilla js can do, and while reinventing the wheel was fun and educational, it didn't result in a better wheel.
Love the website, too bad it doesn't use nor mention the new and much improved DOM APIs.<p>This swap function is just `a.replaceWith(c, d, e, …)` in DOM4<p><a href="https://htmldom.dev/swap-two-nodes" rel="nofollow">https://htmldom.dev/swap-two-nodes</a><p>If you haven't seen this before, I highly suggest looking into it.<p><a href="https://github.com/WebReflection/dom4" rel="nofollow">https://github.com/WebReflection/dom4</a> (I can't find any articles about DOM 4, so this polyfill’s readme will have to do)
I would never recommend copy-pasting this code into your project:<p><a href="https://htmldom.dev/copy-text-to-the-clipboard" rel="nofollow">https://htmldom.dev/copy-text-to-the-clipboard</a><p>I get "trying to stay vanilla", but any reasonably-common snippet should either be installed from npm or published there.<p>For this specific issue there's a module named almost exactly the same and it restores the previous selection and focus as well: <a href="https://github.com/sindresorhus/copy-text-to-clipboard/blob/master/index.js" rel="nofollow">https://github.com/sindresorhus/copy-text-to-clipboard/blob/...</a><p>This is the point of published modules: your code isn't stuck into the version someone wrote in 10 minutes 5 years ago.
Nice collection of recipes! Just a few quibbles about the website design:<p><pre><code> * The back and forward buttons lose scroll position.
* Visited links look the same as non-visited.
* In each recipe, top 70% of the screen is headers and whitespace, bottom 30% is content (on my laptop).</code></pre>
This is a really great set of demos! The resizable table columns really irks me because I spent so long trying to make something similar and it ended up being hundreds of lines longer.
This is nice - it reminds me of the VanillaJS "framework" site - <a href="http://vanilla-js.com/" rel="nofollow">http://vanilla-js.com/</a>
Pretty good! My only wish is that the site would be like <a href="http://youmightnotneedjquery.com/" rel="nofollow">http://youmightnotneedjquery.com/</a>, so that the content would be viewable just by clicking the heading and having new space for it, perhaps in a fixed window, instead of separate pages.
Are there any starter tutorials that would build from vanilla JaveScript, implementing solutions to developer problems, then demonstrating how one might use an existing, well-exercised framework to solve those problems? Every time I go try to learn about a framework from the project web site, they assume a tremendous amount of context.<p>Tangentially, my most recent frustration: I wanted to try a couple frameworks together (they had no overlap in functionality - not like trying to use React and Vue together), and they <i>both</i> came with CLI tools to initialize an empty project and complained when it wasn't empty. They both had different opinions about how to structure project directories, and neither explained in an obvious place how else one might get started.
I started to look into going vanilla JS for a side project and ended up going with Svelte instead. Worth checking out.<p><a href="https://svelte.dev/blog/svelte-3-rethinking-reactivity" rel="nofollow">https://svelte.dev/blog/svelte-3-rethinking-reactivity</a>
It's always worth learning a level lower from what you do, so if you write frontend UIs with React it's worth learning how DOM manipulation works with vanilla JS to understand the intricacies and appreciate what the library abstracts for you.<p>If you start writing a site in vanilla JS you'll eventually end up writing your own UI library basically reinventing the wheel which is fine as a learning experience and personal projects but maybe not the best choice if you're working on a large scale project with many developers since UI libraries and frameworks provide a common set of patterns as convention to follow that makes it easier for everybody to be on the same page.
Great resource. I'm wondering whether the examples are your own or copied from across the web?<p>I just wanted to point out that some of them are a bit outdated, and I belive it'd be nice to maintain this list as a reference with modern approaches.<p>For example, there's no need to use `appendChild`, because DOM today has a more versatile `append` method.<p>And `[].forEach.call(cols, function(col) {...}` would look much better and more declarative as `for (const col of cols) { ... }`.<p>These are just first 2 examples that I noticed.
One of the issues here is that the examples don't add any accessibility hints at all. We really should be encouraging people to add as many as possible!
Slightly unrelated: I am a complete beginner in Javascript, and I was trying it out for a small web-based UI. I was surprised how importing one js into another was non-intuitive. One would need to import all the js's into the main HTML. Feel free to correct me if I am abusing it.
Meta-proposition: why can't I tell Google to weigh results from this (or some arbitrary site) higher after I have confirmed its usefulness? Searching through JS docs is a nightmare filled with outdated libraries and scummy SEO articles... so hard to filter through the noise.
Interesting how the list doesn't begin with use of querySelector or getElementById.<p>I know these sites are made by experts who aren't necessarily thinking about beginners, but a foundation, even a small one, is super valuable.
The trick to manage the DOM with vanilla HTML is to <i>not</i> use HTML! Then abstract code into functions.
The advantage with modern JS frameworks is that they make it easier to handle state, and state handling is usually very hard. The trick to state handling in JavaScript is to make use of closures, to prevent the anti-pattern of global state where you don't know which functions change what state. The only function allowed to change the state should be function that created the element! This can be achieved with event listeners that listens for messages from the server.
This is such a wonderful resource, I wish we had it when first building our app, which uses no frameworks or libs. We do use TypeScript to generate it, hard to pass up the benefits and syntax it provides.
Js Frameworks are built on top of vanilla JS, so if you build an application of any complexity you will eventually start to abstract functionality until you have your own (probably bad) framework.
Ahh thanks. A lot of times you use these fancy frameworks and don't know what's going on at a lower level. Understanding this makes you understand the fancy frameworks faster.
I love this. It doesn't matter what framework you use, having to raw dom manipulation is eventually a task for any seasoned frontend engineer. Understanding the dom api is absolutely essential, when performance is paramount. Resizing tables, drag/drop, e.t.c any advanced interaction will need control of raw dom. Thanks for writing the little recipes.<p>I'm not dissing Frameworks. They are a tool that help you with certain kinds of problems. Any crafts(wo)man, should know their tools well.
DOM diffing is great for most stuff. When you need anything other than "Replace this with that and don't defocus my input fields", DOM manipulations are great. Drag'n'drop is a great example of this.<p>There is a lot of potential for the imperative APIs for this though. I even made a proposal:<p><a href="https://github.com/adrianhelvik/proposal-move-events" rel="nofollow">https://github.com/adrianhelvik/proposal-move-events</a>
I think everyone should know how the DOM works under the hood but the HN hate for frameworks and love for vanilla JavaScript is just unbelievable. As soon as you venture past small JavaScript sprinkle you will regret using vanilla. It feels like a made-up opinion by people who are actually not developing front-end JavaScript seriously. The DOM API is simply unfit for real web apps without a proper framework on top.
I recently did a write-up of my experience with writing maintainable code with vanilla JS: <a href="https://magnushoff.com/blog/dependency-free-javascript/" rel="nofollow">https://magnushoff.com/blog/dependency-free-javascript/</a><p>I am a huge fan of React for the maintainability of the resulting code, and this was my attempt to regain some of that without the dependency.
There's a large range of approaches between a heavy framework like React and vanilla DOM manipulations. jQuery is one such popular solution, and I don't see why such helpers should be completely avoided. Another (full disclosure: I'm the author) is: <a href="http://techlayer.com/espresso.js/" rel="nofollow">http://techlayer.com/espresso.js/</a>
I'd be interested to see if other people have similar go-to vanilla JS? If so, can you share a link here?<p>This one is mine:<p><a href="https://github.com/donohoe/content/blob/master/posts/javascript-returns.md" rel="nofollow">https://github.com/donohoe/content/blob/master/posts/javascr...</a><p>(I follow basic ES6 syntax but easy to switch as needed)
For point 11, checking the bbox can be unreliable. JS got an Intersection Observer API a while back - <a href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/API/Intersectio...</a>
Pretty cool!<p>One thing that would massively improve this is if they were written as singular standalone blocks instead of sparse collections of snippets; I'd like to be able to grab, say, "make an element draggable" and toss it on my codebase as an isolated behavior.
This kind of thing sounds great on personal projects, but doesn't scale. Like many abstractions, frameworks' biggest benefit is (arguably) making it easier for teams to work together.
Excellent. Reminds me of You Might Not Need jQuery [1] from awhile back.<p>[1]: <a href="http://youmightnotneedjquery.com/" rel="nofollow">http://youmightnotneedjquery.com/</a>
Similar site from much longer ago, but with less content:<p><a href="http://standardjavascript.info/" rel="nofollow">http://standardjavascript.info/</a>
This is a great resource. I've had to dig through a lot of StackOverflow threads to figure these out. Great to have lots of current answers in one place.
I'm a vanilla-js guy.<p>That cookbook is pretty good.<p>If anybody has a good way of doing a password dialog in vanilla-js, please post a link.<p>It's the one thing I've encountered where I wish I had used a framework.
This is useful for some devs in some situations, but let's not go overboard. Teaching newbies to venerate vanilla is almost educational malpractice.