About The Author

Vitaly Friedman loves beautiful content and doesn’t like to give in easily. When he is not writing, he’s most probably running front-end & UX … More about Vitaly ↬

Vanilla JavaScript Code Snippets

          In a new series of posts, we highlight some of the useful tools and techniques for developers and designers. This time around, let’s look at vanilla JavaScript code snippets — resources and lightweight libraries to help you solve a problem without a large overhead or third-party dependencies.

          Every now and again we have to deal with legacy code, wading through dark and eerie sides of the code base, often with a vague, ambiguous and unsettling documentation — if any is provided at all. In such cases, refactoring the component seems inevitable.

          Or perhaps you need to manage dates and arrays, or manipulate DOM — there is just no need to add an external dependency for a simple task of that kind, but we need to figure out the best way to do that. It’s always a good idea to explore lightweight vanilla JavaScript snippets as well — preferably the ones that don’t have any third-party dependencies. Fortunately, there is no shortage in tooling to do just that.

          30 Seconds Of Code

          30 Seconds of Code features a huge repository of short code snippets for JavaScript, including helpers for dealing with primitives, arrays and objects, as well as algorithms, DOM manipulation functions and Node.js utilities. You can also find plenty of small utilities for Python, React Hooks, React Components and Node.js. It also features useful JavaScript cheatsheets.

          30 Seconds Of Code
          30 Seconds of Code, with a huge repository of short code snippets and JavaScript cheatsheets.

          HTML Dom

          HTML Dom provides over 120 bulletproof, plain JavaScript snippets for everything from toggling password visibility to creating resizable split views — all supported for modern browsers and IE11+.

          HTML Dom
          120 bulletproof, plain JavaScript snippets, on HTML Dom.

          Vanilla JavaScript Toolkit

          Vanilla JavaScript Toolkit provides a growing collection of vanilla JavaScript methods, helper functions, plugins, boilerplates, polyfills, and learning resources. Also, Chris Ferdinandi runs a Vanilla JS Academy, with plenty of daily developer tips on Vanilla JS sent in his newsletter.

          Vanilla JavaScript Toolkit
          Meet Vanilla JavaScript toolkit, a growing collection of vanilla JavaScript methods and helper functions.

          Migrating from jQuery to Vanilla JavaScript

          If you still find yourself in the land of legacy systems running on jQuery, there is a number of resources that allow you to slowly move away from jQuery with more lightweight and standardized options. One of the excellent guides is Tobias Ahlin’s Cheat sheet for moving from jQuery to vanilla JavaScript, a practical reference guide with some of the most common jQuery patterns and their equivalents in JavaScript.

          Vanilla JavaScript Toolkit
          Meet a practical reference guide with common jQuery patterns and their native JavaScript equivalents.

          There are also many other useful resources worth taking a look at:

          • PlainJS, You Might Not Need jQuery and You Don’t Need jQuery are great references for vanilla JavaScript snippets. The sites feature repositories of code snippets for everything from UI and inputs to media, navigation and visual effects (with use cases not just for jQuery, but pretty much any legacy code).
          • Learn Vanilla JS features books, courses, evergreen resources, communities, podcasts all around vanilla JS. A fantastic repository that’s worth keeping close.
          • JavaScript Framework Diet is Sebastian De Deyne’s ongoing series on common tasks, solved without JavaScript frameworks. You’ll learn about selecting element, event delegation, file structure, dropdowns and enter and leave transitions.

          Micro-Libraries Under 5K

          Micro.js is a curated repository of small JavaScript libraries and utilities, collected by Thomas Fuchs. All libraries are grouped, and are below 5k in size, doing one thing and one thing only — and doin it well.

          Micro-Libraries Under 5K
          Micro.js is a curated repository of small JavaScript libraries and utilities.

          Single Line Of Code

          Phuoc Nguyen has released Single-Line-Of-Code, a repository of JavaScript utilities for everything around arrays, date and time, DOM manipulations, functions, numbers and objects.

          Single Line Of Code
          Single Line of Code, with JavaScript utilities for basic tasks and DOM manipulations.

          Vanilla JS Code Challenge

          30 Days Vanilla JS Code Challenge is a free video course by Wes Bos where you’ll learn to build 30 things in 30 days, with 30 tutorials — without any frameworks, compilers, libraries or boilerplates. That’s a great way to boost your JavaScript skills. You can also get all 30 days challenges and solutions as a GitHub repo.

          Vanilla JS Code Challenge
          30 Days Vanilla Code Challenge, a free video course by Wes Bos.

          Vanilla JavaScript video crash course is another free video course with 43 sessions, starting out with JavaScript DOM all the way to async JS, Babel and Webpack and a JavaScript password generator.

          Vanilla JavaScript Video Crash Course
          Vanilla JavaScript Video Crash Course, a free video course with 43 sessions.

          Natively Format JavaScript Dates And Times

          Do we still need libraries like Moment.js or date-fns to format JavaScript dates and times? With native browser capabilities being quite good these days and browser support being great, too, not necessarily, as Elijah Manor points out.

          Natively Format JavaScript Dates And Times
          Natively format JavaScript dates and times, a thorough guide.

          Elijah summarized three different methods for dealing with time and dates. The toLocaleDateString method comes in handy when you want a date that contains only numbers, a long wordy date, or one that outputs in a different language. If you only need to output the time portion of a JavaScript date object, there’s toLocaleTimeString.

          Finally, the generic method toLocaleString lets you pass one or all of the options from the former ones into one method. Elijah built a CodeSandbox playground where you can experiment with the different approaches.

          this vs. that

          The deep knowledge of a subject really lies in understanding subtle differences between alternate ways of solving the same problem. How is nodeName different from tagName? How are the two increment operators different, e.g. ++value and value++? this vs. that is a friendly reference site for sorting out just this kind of questions.

          this vs that
          this vs. that

          The growing little repository by Phuoc Nguyen explains differences between properties and functions for JavaScript and TypeScript, as well as DOM, HTML and CSS. Also, WTF.js is a growing repository of common headaches, gotchas and unexpected behaviors around JavaScript.

          Writing Clean, Reusable Code

          No one likes to deal with badly written code, but in reality it happens all too often. To help us do better, Ryan McDermott adapted the software engineering principles from Robert C. Martin’s book Clean Code for JavaScript. The result is a practical guide to producing readable, reusable, and refactorable software in JavaScript.

          Writing Clean, Reusable Code
          Clean Code guidelines, with good and bad examples.

          From making variables meaningful and explanatory to limiting the amount of functions and dealing with error handling, the guide compares good and bad code examples. Of course, not every principle has to be strictly followed, but the guidelines help you assess the quality of the JavaScript code you and your team produce.

          JavaScript The Right Way

          Learning a new language can be quite a challenge, especially when there are so many tools and frameworks out there to get the most out of it as there are in the case of JavaScript. To prevent you from getting lost in all the possibilities and help you learn the best practices from the ground up instead, William Oliveira and Allan Esquina put together the guide “JavaScript The Right Way”.

          JavaScript The Right Way
          JavaScript The Right Way, a comprehensive guide.

          Aimed at both beginners and experienced developers who want to dive deeper into JavaScript best practices, the guide gathers articles, tips, and tricks from top developers, covering everything from the very basics to code style, tools, frameworks, game engines, reading resources, screencasts, and much more to make a developer’s life easier. The guide is available in eight languages. A gold mine full of JavaScript wisdom.

          And if you need another deep dive into JavaScript, Kyle Simpson’s You Don’t Know JS is always a good starting point (Kyle is working on the second edition at the moment, and also has plenty of books and video courses to explore).

          Picking The Right JavaScript Framework

          There are plenty of options when choosing a new JavaScript framework. But do you need one? And if so, how do you pick the right one? Sacha Greif’s 12-Points-Checklist highlights 12 things to keep in mind when evaluating any new JavaScript library. Most notably, features, performance, learning curve, compatibility and track record.

          Picking The Right JavaScript Framework
          It's a good idea to study the impact of JavaScript frameworks, with Perf-Track.

          Perf-Track tracks framework performance at scale. It basically tracks the performance in terms of Core Web Vitals for Angular, React, Vue, Polymer, Preact, Ember, Svelte and AMP — on mobile and on desktop. The data set is currently still from 2020, but it gives us some insights into how well sites with these frameworks perform in the wild. For example, React with Gatsby perform better than the ones created with Create React app.

          Tim Kadlec also conducted some research around that, comparing jQuery, Vue.js, Angular and React. The end result: the current crop of frameworks isn’t doing enough to prioritize less powerful devices and help to close the gap between desktop and mobile. These figures might give you at least some context to make a more informed decision.

          Standalone Vanilla JS Libraries

          The libraries below are tiny, vanilla JavaScript libraries without any dependencies. Just as they are lightweight, sometimes you might need to make some adjustments, e.g. to provide announcements to screen readers, or support legacy browsers. You might want to check a Complete Guide To Accessible Front-End Components as well.

          • 360-degree view
            ThreeSixty.js is a tool for turning an image sprite into 360 degree image.
          • Animation
            Anime.js is a lightweight animation library that works with CSS properties, SVG, Dom attributes and JavaScript objects. Also, Sal.js is a lightweight scroll animation library.
          • Data Visualization
            Clusterize.js is a small JavaScript library for displaying large data sets.
          • Filtering
            MixItUp 3 provides animated filtering, sorting, insertion and removal.
          • Forms
            Choices.js is a configurable <select>-box/text input plugin.
          • Image full screen preview
            Intense Image Viewer, a library for viewing images in full screen.
          • Image gallery
            PhotoSwipe, supports touch gestures and Browser History API.
          • Masonry Layout
            Columns.js and Waterfall.js are options for Masonry layout written in Vanilla JavaScript.
          • Media Player
            Media Player, a cross browser, accessible, customizable media player written in plain JavaScript.
          • Modals
            accessible_modal_window by Scott O’Hara.
          • Parallax
            Rellax.js is a lightweight vanilla JavaScript parallax library (if you absolutely need one).
          • Reactive states
            Reef, a lightweight library for creating reactive, state-based UI.
          • Search
            InstantSearch.js is an an open-source UI library that lets you build a search interface in your front-end application.
          • Sliders and carousels
            Siema, Glide, Splide.js and Swipe.js.
          • Slideout navigation
            Slideout.js is a touch slideout navigation menu for mobile views.
          • Spinners
            Spin.js dynamically creates spinning activity indicators, no images or dependencies needed, distributed as a native ES module.
          • Sticky elements
            HC-Sticky makes any element on the page visible while a custom is scrolling. (Also consider using position="sticky" in CSS instead).
          • Sticky navigation
            MenuSpy, a small JavaScript for sticky navigation bars that change as a user scrolls pas the parts of the page.
          • Table filters and lists
            List.js adds search, sort and filters to plain HTML lists and tables.
          • Table sorting
            Tablesort is a simple sorting component for tables.
          • Transitions
            Barba.js is a great alternative to parallax, with fluid and smooth transitions between pages.
          • Tilting
            Tilt-Vanilla.js is a smooth 3D tilt JavaScript library.
          • Typewriter Text Effect
            Typewriter JS generates a typewriter effect.
          • Visual sparkles
            Speckle.js is a JavaScript module that adds responsive, stylized speckles to any element.
          • WYSIWIG Text Editors
            Froala, Etherpad and SunEditor are vanilla JavaScript WYSIWIG text editors. And if you want to build your own, ContentTools is a library for building WYSIWIG editors for HTML content.
          Smashing Editorial (il)