32 ms·
How to manage HTML DOM with vanilla JavaScript only?
- niyazpk 7y ago>> "for modern browsers and IE 11+" Ouch!
- jjcm 7y agoI feel like Safari should be included in there as well. Safari is the new IE, they're so slow in adopting new specs. With IE having moved to chromium and Firefox having solid contributions to the spec and always being on the bleeding edge, we were bound to see the it be the one fall behind given Apple's slower cadence, but I've been amazed at how much of a blocker it's been.
- baybal2 7y agoProtip: https://developer.mozilla.org/en-US/docs/Web/API/XSLTProcessor https://developer.mozilla.org/en-US/docs/Web/API/XSLTProcess...
- michaelbuckbee 7y agoThis is nice - it reminds me of the VanillaJS "framework" site - http://vanilla-js.com/ http://vanilla-js.com/
- guggle 7y agoThat's great ! Very useful.
- Waterluvian 7y agoInteresting how the list doesn't begin with use of querySelector or getElementById. 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.
- hk__2 7y agoThe list is in alphabetical order, so “Select an element or list of elements” is down with the other S’s: https://htmldom.dev/select-an-element-or-list-of-elements https://htmldom.dev/select-an-element-or-list-of-elements
- emilfihlman 7y agoThat's a big oversight, the list should be in the order of learning.
- diggan 7y ago> but a foundation, even a small one, is super valuable Well, I mean, first example is "ele.classList.add('class-name');", beginner or not, you gotta understand where `el` is coming from. Seems like a big oversight to have incomplete samples, even from the first example.
- zoom6628 7y agoThis 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.
- deleted 7y ago[deleted]
- dgb23 7y agoI agree! The MDN docs are from my experience the best browser frontend reference available. This site however covers a different need: guide/howto oriented documentation, which is often what you want. > Doing & Learning things in plain JS we can learn fundamentals. To this I have to add that I often do write plain JS supported by only a few, small libraries such as is.js, axios, json-schema and so on. This is regarding small to medium sized projects and/or features. This can easily save time, setup and mental energy, as long as one follows a consistent, simple structure. And on top of that, the fewer dependencies you have, the less friction. But it also means that one has to have a bit of a deeper knowledge of the available frameworks and tools, which can manage complexity with growing features, because you add them incrementally and only when needed and so on.
- Kwantuum 7y agoHonestly, while axios is nice to have on the server side, the websocket API in the browser is very simple to use. Which IMO is a consistent theme with modern browser APIs.
- redis_mlc 7y agoI'm a vanilla-js guy. That cookbook is pretty good. If anybody has a good way of doing a password dialog in vanilla-js, please post a link. It's the one thing I've encountered where I wish I had used a framework.
- 101008 7y agoSorry, what's a password dialog?
- omgwtfbbqhihihi 7y agoA dialog box that prompts for your password. Never seen one?
- satvikpendem 7y agoLike <input type="password">? Or something more complex?
- ken 7y agoThat’s a password field. Now just put it in a <dialog>.
- satvikpendem 7y agoWhat's the problem exactly? I assume you looked into putting that input element inside a dialog element and it didn't work, is that the issue?
- redis_mlc 7y agodialog is not supported on Firefox and Safari without a polyfill.
- draw_down 7y agoTurns out those stupid things come in handy sometimes!
- hk__2 7y agoIronically, the site itself uses ~100ko of gzip’d JS.
- zeusly 7y agoAnd is built in react. It's about choosing the right tool for the job.
- hk__2 7y ago> And is built in react. It's about choosing the right tool for the job. React is useless here. Try browsing the website without JS and notice how litterally nothing changes. The only things that need JS are the light filter at the top and the fast navigation using body/head swapping + pushState, none of which require React.
- dubcanada 7y agoOn the frontend, yes. But it seems that it does server side compiling. So basically the frontend JS is so the backend can produce HTML. Rather weird way of looking at it.
- Kiro 7y agoIf anything this reminds me why I'm using React. Having to manually add and remove children, classes or anything dynamic is just a pain.
- donohoe 7y agoI'd be interested to see if other people have similar go-to vanilla JS? If so, can you share a link here? This one is mine: https://github.com/donohoe/content/blob/master/posts/javascript-returns.md https://github.com/donohoe/content/blob/master/posts/javascr... (I follow basic ES6 syntax but easy to switch as needed)
- tyingq 7y agoA vanilla JS replacement for jQuery's ajax functionality, that worked on older browsers, would be welcome. Edit: To clarify, a drop in replacement is what I was looking for.
- validuser 7y agohttp://youmightnotneedjquery.com/#ajax http://youmightnotneedjquery.com/#ajax
- untog 7y agoFor me the Fetch API is basically that: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API fetch("http://www.example.com").then(res => res.json()).then(json => {}) Only big downside is no IE11 support but thankfully I don't have to worry about that so much these days.
- henriquez 7y agoNice work. I was looking for something just like this!
- KaoruAoiShiho 7y agoThis is useful for some devs in some situations, but let's not go overboard. Teaching newbies to venerate vanilla is almost educational malpractice.
- bob1029 7y agoTeaching newbies that they can gloss over fundamental details with some extra NPM commands is certainly educational malpractice IMO.
- deleted 7y ago[deleted]
- untog 7y agoIt really isn't. Teaching newbies to venerate JSX and React is far more harmful in my opinion: it does a really good job of hiding what's actually going on. These days vanilla JS DOM APIs are pretty straightforward. It's well worth learning them and using them on small projects where a library like React is absurd overkill.
- nessunodoro 7y agoUnderstanding fundamental browser behavior serves the purpose of optimizing CPU and bandwidth. Think of it as the bare metal of the browser
- krapp 7y agoWhat is tantamount to educational malpractice is the pathological revulsion javascript developers have for their own language, such that merely teaching newbies how to actually write it without six proxies, three other languages and a framework to protected them is considered harmful.
- Finnucane 7y agoSure, either Javascript is an intrinsically good language, and you should therefore be able to use it as is, or it is not good, in which case the sane response would be to use it as little as possible. Every language has warts, but most can at least go out in public without layers of makeup.
- emilfihlman 7y agoPretty good! My only wish is that the site would be like http://youmightnotneedjquery.com/ http://youmightnotneedjquery.com/, 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.
- cousin_it 7y agoNice collection of recipes! Just a few quibbles about the website design: * 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).
- thanatropism 7y ago* The text on this kind of code block is annoying to read even on a 15" laptop with only a slightly enlarged font.
- krossitalk 7y agoThis 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.
- edroche 7y agoThis 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.
- caseymarquis 7y agoI 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. 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). 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. 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.
- draw_down 7y agoThat’s right!
- Kwantuum 7y agoAlternatively, you can use a simple web-server without needing all of webpack: using npx (included with npm): npx serve . using the php CLI: php -S localhost:5000 -t . You weren't hitting the limits of vanilla JS, you were hitting the limit of reading files directly from disk instead of through a web server.
- Dangeranger 7y agoThis is a good point, the fact that browsers won’t load JS modules over the file:// protocol is not the fault of JavaScript.
- staz 7y agoor in python 2 (should be on installed by default on most distro): python -m SimpleHTTPServer or python3 : python -m http.server
- 7y ago
- austincheney 7y agoCoincidentally, I just commented yesterday about an interview experience I had about the DOM. I did not expect it to be so highly upvoted. https://news.ycombinator.com/item?id=22740897 https://news.ycombinator.com/item?id=22740897
- dahart 7y agoI don’t know if I would pass your test, but the outcome is more or less exactly what I would have expected. The vast majority of employed web devs do not use pure JS to manipulate the DOM because it’s incredibly tedious. That was true 5-10 years ago when the most popular option was JQuery, and now we have massive swaths of React where people don’t manipulate the DOM directly at all. And they get by just fine. Major commercial sites are built with little to no direct DOM manipulation. Saying that you’re going to let people have time, use the web to lookup the answer, that there’s no penalty, etc., that seems blind to the fact that you’re signaling what it takes to pass the test as well as what people will be doing once they start working for you. I’m certain you lost the opportunity to interview some good candidates simply because they are choosing to not work somewhere that thinks pure JS is the only performant solution, and might not know that there are both good and bad ways to use JQuery, and/or functional reactive solutions that avoid keeping messy/buggy state around when you could instead re-render. I’m sure you also lost interviews because some candidates were basically told by you that already knowing how to manipulate the DOM via pure JS was what was required to ace the interview. They assumed, and reasonably so, that spending the hour showing you they didn’t already know how would result in not getting a job, so why bother with the interview right now? You might have sent several smart people off to study and do homework about it, but you don’t know that because they walked out the door. So, while I do think it’s very useful to know how to use pure JS on the DOM, and I think your interview experience is interesting, the incredulity about it makes it seem to me like you’re not entirely taking responsibility for the implicit message that you sent to your candidates for the interview, nor that the outcome is fairly predictable.
- austincheney 7y agoThe job position was for people to write A/B tests. A/B tests are a form of white hat hacking where code is injected into a page to manipulate or deface the page to test a business idea as an experiment. It would not make sense to inject something like Angular or React as part of test code and would be detrimentally regressive to inject Angular or React targeted logic over an existing framework application without a more thorough consideration for second and third order consequences. An experiment is meant to be something that is created with the least possible labor since its not production code and short lived. That said the most desirable approach was to manipulate the DOM directly since this achieved the fastest execution, provided the smallest risk/footprint, and was fastest to QA for regression. --- In hindsight we learned a couple of things from A/B testing. * In a page with a lot of asynchronously loading content everything can be precisely altered before the user can notice it. The more precise form of delay were recursive setTimeouts where the interval delay could be manually adjusted to the millisecond and there was never interval overlap. This took practice to know when and where to increase the interval rate without impacting the performance of other logic already in the page. * The tests did not often reflect the actual business results compared to the production code written later. We found the test logic, even though it was just hacky throwaway code, was generally less defective and faster executing than the more thoroughly tested production code and so performed better than the actual results from the formally released code.
- Kiro 7y agoI 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.
- cloverich 7y agoIts hard to see why the JS frameworks came to be, and easy to see the up front complexity of most of them. People who started before good frameworks were around take it for granted that people know what happens when you build complex sites with vanilla JS: You get a mess, or you get your own framework.
- marcosdumay 7y agoNot everybody wants to render everything on the client. JS frameworks (vue included, despite trying) do just not support rendering as a simple page. Some people do have light needs that won't ever require a full framework. Other people have very heavy needs that will require their own frameworks. The JS ones (react included) are not absolutely flexible. And, if you fit none of those categories (honestly, most people are on the first), just replace the title with "how does a JS framework operate on the DOM", and take it as a learning resource.
- Kiro 7y ago> Not everybody wants to render everything on the client. No, and then you should just render it on the server. Most "apps" should not be JavaScript apps at all. However, once you do need to enter that territory you should definitely use a front-end framework.
- robertoandred 7y ago> JS frameworks do just not support rendering as a simple page. What is this supposed to mean?
- droobles 7y agoI do all my personal mvps now in vanilla JS, I can get ideas fleshed out faster without fumbling over frameworks.
- mschuster91 7y agoOut of random interest, not even jQuery? I find it immensely tedious to write out vanilla js compared to all the shortcuts that $ provides...
- xingyzt 7y agoQuerySelectorAll is widely supported and you can make your own shorthand for it. function $(query) { const result = document.querySelectorAll(query) if ( result ) { if ( result.length > 1 ) { return result } else { return result[0] } } }
- bfred_it 7y agoI hope you don't use that since it randomly returns either an element or a list of elements, so you'd have to also add an if/else every time you use it. This is my go-to: const $ = document.querySelector.bind(document); const $$ = document.querySelectorAll.bind(document); Tip: browser consoles already have these shortcuts, except $$ returns an actual array there instead of a NodeList.
- mellow2020 7y agoKnowing that jQuery ends up calling those very same functions, only often after jumping through a bunch of hoops, doesnt make me consider it a shortcut. Between auto-complete and copy and paste, I prefer slightly more "work" up front, and then zero needless work at runtime, than a bit of "magic" that ends up doing needless work every single time it is run. But I have to admit, I don't care about compatibility beyond Firefox on the desktop, if I wrote stuff for a company on a deadline, or if I worked with other people on something, I would mind jQuery very little or not at all. But for my own stuff I make to spark joy, where I get to decide all of it, I want it as vanilla as I can get it.
- vbezhenar 7y agoThe 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.
- dexwiz 7y ago> just have to follow good practice Easier said than done when best practices shift every 6 months.
- bernardv 7y agoThe problem is that the Wild West and unnecessary complexity has just been shifted up a level or two as devs are now facing the Wild West of frameworks, de ops has turned into a monster with an unnecessary large toolbox.
- protonimitate 7y agoAgreed. This is my main issue with the "you don't need frameworks" rhetoric. If you're a small team or a solo dev working on a simple app, and you know the source code very well, frameworks might not be the best choice. However, if you've ever worked on a team of revolving contributors, constantly shifting requirements, or have any reason to reuse code across apps/repos, frameworks help immensely. The biggest benefit to using something like React imo, is that when we hire somebody familiar with React, they can hit the ground running and start contributing immediately. Unless your app is dead simple, you won't be able to have the same velocity in a homespun framework (and given enough time, most "vanilla" apps turn into homespun frameworks).
- mettamage 7y agoIsn't this also simply true in the corporate world in general? Frameworks and best practices of doing something means that things are standardized. Standardization means that a vocabulary is shared and people understand each other. You want to make people as swappable as possible. At least that's how I look at it from a management perspective (not a manager, but one can dream).
- deleted 7y ago[deleted]
- Leace 7y agoInteresting pattern, first time I saw this: switch (true) { case cellA > cellB: return 1; case cellA < cellB: return -1; case cellA === cellB: return 0; } Source: https://htmldom.dev/sort-a-table-by-clicking-its-headers https://htmldom.dev/sort-a-table-by-clicking-its-headers
- planb 7y agoI had to think for a sec to get this. And this already makes it worse than 3 if statements. Does anyone really find this more readable?
- robto 7y agoComing from a lisp I often wish other languages had `cond` so I don't have to nest if statements. This looks like a poor man's cond. So yes, I do find this more readable. It makes it clear that only one branch will get executed.
- foldr 7y agoThis would be equally clear if the author had just used a sequence of if statements with a 'return' in each one. (Note that Javascript's case has fallthrough, so you can't immediately conclude that only one branch of a case will be executed.)
- hombre_fatal 7y agoYou don't have to nest if-statements and I would say nested-if is wrong. You simply use else-if. It's a flat structure just like cond.
- TheRealPomax 7y agoyou mean two if statements. The last case is a default return.
- hacker_9 7y agoInteresting at first glance, but what is the performance of this? It looks like all cases would have to be evaluated before picking one, so even slower than an if-else-if.
- jnet 7y agoele.classList.toggle('class-name'); That seems really useful, and I had no idea it existed.
- abdusco 7y agoYou can also give it a second boolean argument to force add/remove classes. let flag = false; ele.classList.toggle('has--flag', flag); will remove the class, for example. https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/toggle https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenLis...
- stasgavrylov 7y agoGreat resource. I'm wondering whether the examples are your own or copied from across the web? 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. For example, there's no need to use `appendChild`, because DOM today has a more versatile `append` method. And `[].forEach.call(cols, function(col) {...}` would look much better and more declarative as `for (const col of cols) { ... }`. These are just first 2 examples that I noticed.
- drdec 7y agoYour proposed changes are not supported in IE 11. The snippets are advertised as IE 11+ compatible on the landing page.
- stasgavrylov 7y agoYou're correct, but let/const don't have full support in IE11 either. I understand that people are still supporting IE, but still, this website could stay relevant longer if the examples were written in ESNext.
- cfv 7y agoPretty cool! 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.
- deleted 7y ago[deleted]
- davnicwil 7y agoGreat resource, I've bookmarked it. You know where vanilla JS still has a legitimate usecase in the era of SPAs? Landing pages. - Mostly static HTML, time to first render is critical, all you want is a little bit of (progressively added) flair - Can be inlined for instant loading/execution, no bundle download (or SSR) necessary - Code has low volume and scope so structure / spaghetti isn't a concern - 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 very quickly
- Lammy 7y ago- You can include a deferred reference to a resource you want to be cached for other pages, like web fonts
- zemnmez 7y agoyou can get all these benefits by pre-rendering and hydrating using a system like react-snap. this means static rendered html is served and the react control is then re-added, or ‘hydrated’ into the DOM content
- gboss 7y agoDepending on how "hydration" is done it can still waste cpu cycles and hurt time to interactive on mobile devices.
- bryanrasmussen 7y agoare you sure you can get all these benefits? - 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 very quickly I mean sure I guess I could do a lot of extra work to separate it out, it's true. But the real benefit of a vanillajs landing page is stuff is simple, and getting all the benefits by pre-rendering and hydrating using a system like react-snap sounds difficult. If we follow the old saying Simple things (to say) should be simple (to do) it implies to me that Difficult things to say will be (relatively) difficult to do.
- bin0 7y agoThis 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.
- TheRealPomax 7y agoFor point 11, checking the bbox can be unreliable. JS got an Intersection Observer API a while back - https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API https://developer.mozilla.org/en-US/docs/Web/API/Intersectio...
- divbzero 7y agoExcellent. Reminds me of You Might Not Need jQuery [1] from awhile back. [1]: http://youmightnotneedjquery.com/ http://youmightnotneedjquery.com/
- pxtail 7y agoWhich is quite funny as it serves as very good demonstration why one should use jQuery: most of presented examples are 10 times more longer when it comes to code amount or alternatively there is some weird oneliner. All of that for saving 30KB of battle tested cross browser code.
- hombre_fatal 7y agoThough note that it doesn't demo anything that only works in IE11+. It doesn't even demo window.fetch(). It's a pretty poor reference for most people. For example, you have no reason to be defaulting to XMLHttpRequest for http requests.
- jancsika 7y ago> This approach isn't recommended because we can only attach one handler for each event. Except when you do 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. 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. 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. So the recommended behavior does not include in its design the ability to achieve the useful old behavior. But at least DOM does have a convenience method to toggle class that will save a good 10 seconds per year of dev time.
- tln 7y agoWhat's the context for that quote? The main page of the linked site doesn't have it. I was wondering something similar while looking at https://htmldom.dev/toggle-password-visibility https://htmldom.dev/toggle-password-visibility This could be done inline with <input type="password" id="password" /> <button onclick="password.type = password.type == 'text' ? 'password' : 'text'">Toggle</button> ...instead of 10 lines of code. Is it ever ok to use the fact that window.elementID works? even for exposition? (it works in all browsers, not sure if its standardized...) Why use setAttribute? Again, setting via element.type = ... works in all browsers.
- austincheney 7y agoIt does. https://htmldom.dev/attach-or-detach-an-event-handler https://htmldom.dev/attach-or-detach-an-event-handler The idea behind addEventListener is that multiple handlers can be attached to the same event of the same node, whereas before handlers were property assignments that would clobber each other. The disadvantage of addEventListener is that event handlers are associated with event listeners instead of with DOM nodes, which makes them more challenging to garbage collect and thus increases the memory space of your application. The way to keep the code clean is to use removeEventListener when the handler is no longer needed. Event handlers are rarely removed from the code though, because of a lack of discipline and because many times its hard to tell when they are no longer needed. The biggest advantage of assignment by property approach is that it imposes simplicity. Simplify means to make fewer and complicate means to make many. When there is only one handler it is inherently the most simple approach, which greatly increases code cleanliness and forces a greater concern of code organization.
- z3t4 7y agoThe trick to manage the DOM with vanilla HTML is to not 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.
- evo_9 7y agoI started to look into going vanilla JS for a side project and ended up going with Svelte instead. Worth checking out. https://svelte.dev/blog/svelte-3-rethinking-reactivity https://svelte.dev/blog/svelte-3-rethinking-reactivity
- baristaGeek 7y agoAhh 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.
- kennydude 7y agoOne 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!
- woranl 7y agoFramework comes and goes. What’s cool today will become obsolete many years later. Vanilla code has less dependencies.
- ericmcer 7y agoJs 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.
- 40four 7y agoFramework debates aside, if you’re looking to do something in pure JavaScript this looks like a great resource! Bookmarked :)
- bfred_it 7y agoI would never recommend copy-pasting this code into your project: https://htmldom.dev/copy-text-to-the-clipboard https://htmldom.dev/copy-text-to-the-clipboard I get "trying to stay vanilla", but any reasonably-common snippet should either be installed from npm or published there. For this specific issue there's a module named almost exactly the same and it restores the previous selection and focus as well: https://github.com/sindresorhus/copy-text-to-clipboard/blob/master/index.js https://github.com/sindresorhus/copy-text-to-clipboard/blob/... This is the point of published modules: your code isn't stuck into the version someone wrote in 10 minutes 5 years ago.
- rsuelzer 7y agoThere are downsides to use package libraries as well. Like: 200mb hello world applications, or some companies restrict npm packages for security reasons. Or, you just want to write code in notepad.exe. There is benefit to simplicity in many cases.
- bfred_it 7y agoIt's up to you to chose reasonable modules by reasonable developers. Notice I didn't call it a library, it's a 1kb module that has the code from the example + fixes you'd want anyway.
- kllrnohj 7y ago> I get "trying to stay vanilla", but any reasonably-common snippet should either be installed from npm or published there. And that's how you end up with the joke that was left-pad and the broken internet that resulted when the author yanked it. Dependencies represent a real risk to your product. If it is actually a simple snippet, you shouldn't take that as an NPM dependency - the risk/reward ratio is just way out of whack with that.
- AgentME 7y agoNPM disallowed un-publishing modules within a few days of that incident. It's not a thing that happens any more. Also, NPM for years has defaulted to creating lockfiles with all the specific versions of dependencies pinned, so even if a dependency gets updated to have a bug, you will stay on the currently-pinned version unless you specifically change that.
- turnipla 7y agoLove the website, too bad it doesn't use nor mention the new and much improved DOM APIs. This swap function is just `a.replaceWith(c, d, e, …)` in DOM4 https://htmldom.dev/swap-two-nodes https://htmldom.dev/swap-two-nodes If you haven't seen this before, I highly suggest looking into it. https://github.com/WebReflection/dom4 https://github.com/WebReflection/dom4 (I can't find any articles about DOM 4, so this polyfill’s readme will have to do)
- tabtab 7y agoMaking 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 exactly match the napkin because you were in charge of exactly where things went. (Layout engines were optional then.) 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". 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. 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. Something is wrong.
- jcmontx 7y agoThe dogmatic React crowd is going to jump on your neck
- DevKoala 7y agoI am not a fan of React, but there is nothing about it that exacerbated the problems OP is talking out. The web’s layout engine is just a PITA. I also feel much more in control inside a canvas. I can do anything I want inside it. However, DOM manipulation is not a solution to layout issues, so I am not sure the OP’s gripe is that relevant to this tutorial.
- aidos 7y agoNone of this has anything to do with react.
- 7y ago
- jborichevskiy 7y agoMeta-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.
- hnrodey 7y agofiltering results by domain has been around for many years. site:htmldom.dev search terms here
- jborichevskiy 7y agoYes of course, but that would involve managing a list of resources and sites. I suppose one master list would be ok across a range of topics but still seems a little cumbersome. Maybe could be built as an extension.
- deleted 7y ago[deleted]
- mattlondon 7y agoSimilar site from much longer ago, but with less content: http://standardjavascript.info/ http://standardjavascript.info/
- maggit 7y agoI recently did a write-up of my experience with writing maintainable code with vanilla JS: https://magnushoff.com/blog/dependency-free-javascript/ https://magnushoff.com/blog/dependency-free-javascript/ 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.
- fourier_mode 7y agoSlightly 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.
- jagged-chisel 7y agoAre 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. 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 both 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.
- gen220 7y agoIt's a difficult place to start from, because a lot of react tutorials are out of date, misleading, shallow, or deep in useless ways. I think most people learn these frameworks by being put to work on a mature code base with established patterns, that already uses a set of frameworks. At first, you kind of don't understand the control flow, but you get better week over week from there. Over time, you are bootstraping your own opinions by asking questions and learning hands-on. Eventually, you can start a project from scratch including the minimal dependencies yourself, as you learn what's actually useful, vs what's "the same interface, but dressed for business". That being said, I'd recommend getting started with `create-react-app`, and following some of the tutorials. I'd then recommend jumping into hooks (https://reactjs.org/docs/hooks-intro.html https://reactjs.org/docs/hooks-intro.html) as soon as possible, unless you have to maintain an older codebase that uses classes, because in "modern" react code, you're almost never using classes any more, and that reality bomb is not typically dropped on you in most react tutorials.
- draw_down 7y agoI searched this for the word "test"; it does not appear. No sweat if testing is not in scope for this particular site, but regardless of your dependencies or approach, writing tests for your code is vital. (The word "test" also doesn't appear in these comments, except for a discussion of A/B testing. Hmm!)
- miguelmota 7y agoIt'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. 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.
- adrianhel 7y agoDOM 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. There is a lot of potential for the imperative APIs for this though. I even made a proposal: https://github.com/adrianhelvik/proposal-move-events https://github.com/adrianhelvik/proposal-move-events
- nojvek 7y agoI 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. 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.
- justlexi93 7y agoThis is really important. It is now feasible to use vanilla JS to work on various scenarios, but a lot of devs don't know this and mindlessly start their projects with jQuery.
- deleted 7y ago[deleted]
- chpmrc 7y agoIronically that website is built in React.
- akrymski 7y agoThere'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: http://techlayer.com/espresso.js/ http://techlayer.com/espresso.js/
- stevedekorte 7y agoThis 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.
- wilsonbright 7y agoGreat resource. Well built and it is going to helpful to many.