Learn JavaScript by Example: Tutorials, Code Snippets & How-To’s

Learn JavaScript in simple and easy steps starting from basic to advanced concepts, with examples including JavaScript tutorials, code snippets, use cases and scenarios.
Vanilla JavaScript or plain JavaScript does not require any third-party libraries or frameworks, and it offers, natively, prototype-based objects, AJAX animations, events, regular expressions, functions as first-class objects, closures, maths libraries, array libraries, string libraries, promises and more.
Also check our JavaScript blog for more resources and tutorials.
Do you need to enable JavaScript in your browser?
Featured guides & hubs
Hand-picked, in-depth guides to start with:
- HTML5 Canvas tutorial series — an 11-part walkthrough from your first draw to a full drawing application.
- Vanilla JavaScript Cookbook — 18 dependency-free, jQuery-free snippets for the everyday tasks.
- JavaScript Sliders collection — vanilla JS sliders, carousels and range controls.
Tutorial series & guides
Start here. These three hubs collect my longer-form JavaScript material into guided paths:
- HTML5 Canvas series — an 11-part walkthrough from first shapes to a full drawing app.
- Vanilla JavaScript Cookbook — copy-paste snippets for everyday tasks, no jQuery required.
- Sliders & carousels — build a lightweight slider from scratch in under 100 lines.
JavaScript reference & snippets
Every standalone tutorial and snippet, grouped by topic so each one is a single click away.
Arrays & data
- A collection of modern native JavaScript object and array utilities
- Calculating Mean, Median, and Mode in JavaScript
- Check DNS records in bulk using JavaScript
- Code Golfing Tips & Tricks: How to Minify your JavaScript Code
- Dropdown Autocomplete with contenteditable Fields
- Enhancing <select> Dropdowns: Removing Duplicates and Sorting Options with Vanilla JavaScript
- Giving Object Context to Function Calls
- Grouping Arrays in JavaScript with Object.groupBy() and Map.groupBy()
- How and Why to Avoid ‘for’ Loops
- How to code your own JavaScript de-duplicator
- How to create a simple JavaScript percentage graph (or chart)
- How to Lazy Load Google Map Iframe Embed in WordPress
- How to Populate OpenStreetMap with Foursquare Venues/Amenities
- JavaScript Data Types
- JavaScript Terminal
- JSONify Dropdown Element Using Vanilla JavaScript
- Self Documenting Flexible Parameters
- Sort Elements Based on Data Attributes with Vanilla JavaScript
- Sorting and Ordering Elements Based on Data Attributes with Vanilla JavaScript
- The Complete JavaScript Strings Reference
- Vanilla JavaScript table date sorting
JSON
- A JSON Overview
- A simple JavaScript suggestion autocomplete app
- Convert jQuery.get() to Vanilla JavaScript
- Creating an Autocomplete Search Feature Using Vanilla JavaScript
- End of an Era: Travel SEO
- How to replace jQuery.ajax() with vanilla JavaScript in WordPress
- How to set up your own Google CrUX report
- Native Browser Support for JSON
- Passing Arguments to External JavaScript Files
- Ping a Remote PHP File and Store Data in a MySQL Database with JavaScript
- Same-Origin AJAX Request Using Vanilla JavaScript
- Thoughts on Instant Loading in WordPress
- WordPress Responseless XHR Request Using JavaScript
Numbers & dates
- 24-Hour Countdown with Progress Saving Using Vanilla JavaScript
- Date Countdown Using Vanilla JavaScript
- How to add a top bar countdown for your next product sale
- How to Compare Version Numbers in JavaScript
- How to create time constants in JavaScript in a performant way
- How to extract a value from an element and, optionally, round it
- How to Measure Page Loading Time with JavaScript
- How to Open Only One Details/Summary Element at a Time
- How to show an outdated browser alert on Internet Explorer 11
- How to track and measure phone number views with JavaScript
- JavaScript Numbers: A Modern Reference
- JavaScript Random String Generator
- Random Imgur Images Using Vanilla JavaScript
- Random JavaScript Tutorials
- Use ‘this’ Keyword with setTimeout()
DOM & events
- A Quick Introduction to Custom Data Attributes and Vanilla JavaScript
- Animated JavaScript Counter-Up with the Intersection Observer API
- Building a Simple Tab Strip using Vanilla JavaScript
- Carbon: Basic Syntax Highlighting with Zero Overhead Using JavaScript
- Client-Side JavaScript Pagination
- Cross-browser Query Parameter Getter and Setter
- Custom Events in JavaScript MVC
- Cutting Loose: Dynamic Namespacing in JavaScript
- DragonflyJS – Vanilla JavaScript Drag and Drop
- Drift Chat: Speed Up Your Page Loading Speed by 3-4 Seconds
- Encapsulation: Private and Public Methods
- Encapsulation: Private Attribute
- Equal Height for All Elements Using Vanilla JavaScript
- Generate a Password Using Vanilla JavaScript
- How and why I added a circle following my mouse pointer
- How I added a neat effect in 30 lines using IntersectionObserver
- How to Autoplay a Video Element Using JavaScript
- How to Build a Double Off-Canvas Menu Using JavaScript
- How to Build a Vertical Off-Canvas Menu Bar Using JavaScript and CSS
- How to check scroll depth using JavaScript
- How to Create a GDPR Modal Popup Using RoarJS
- How to Create a JavaScript Typewriter Using Vanilla JavaScript
- How to Create a Price Range Slider Using Vanilla JavaScript
- How to Create a Programmatic JavaScript Tooltip
- How to create a YouTube video cover using the YouTube Iframe API
- How to Create an Internationalisation System Using JavaScript
- How to Declare a Global Variable inside a JavaScript Function
- How to execute code for X visits
- How to Get and Set URL Parameters with JavaScript
- How to Implement a Service Worker in Your Website and How to Create a Basic PWA
- How to Make an Iframe Responsive Using JavaScript
- How to Optimize a Theoretical Funnel Page Load Speed
- Image Beacons
- Implementing Custom Tooltips with Vanilla JavaScript
- JavaScript Bookmarklets Collection
- JavaScript Character Counter for Text Areas
- JavaScript Credit Card Validation
- JavaScript Drag & Drop
- JavaScript Form Validation
- JavaScript Marquee: A collection of scrolling text snippets
- JavaScript Selectors API
- JavaScript shortcuts for TRUE and FALSE
- JavaScript String Multiline Trim/Cleanup
- John Resig’s Inheritance
- Native JavaScript Drag&Drop Upload
- Numerical Integration Using JavaScript
- Promises in JavaScript
- Pure JavaScript tabbing functionality with linkable tabs
- RoarJS – JavaScript Alert/Confirm Replacement
- Segmented Horizontal Bar Chart (Graph) Using Vanilla JavaScript
- SEO Crawlability Issue: Resources are formatted as page link
- Simplifying Conditional Statements in JavaScript with the && Operator
- StackGrid — A Light Vanilla JavaScript Masonry Grid
- Switching From JavaScript to PHP for Browser Detection and Avoiding Core Web Vitals Penalties
- tail.select
- Thin Select — Custom JavaScript Dropdown Element
- Trigger an Event When User Reaches the Bottom of the Page
- truthy and falsy in JavaScript
- Understanding JavaScript Currying
- Useful JavaScript String Prototypes
- Why I removed my dark theme switcher
Misc
- A Trio of Approachable Vanilla JS Sliders
- Fast and accessible JavaScript client logo carousel
- How to Add Voice Search Capability to Your WordPress Site
- How to Create a Draggable Carousel using Vanilla JavaScript
- How to Create a JavaScript Spinner with Phenakistoscope Effect
- How to Enable JavaScript
- How to Replace Slider Revolution with Flickity and Gain 50+ Performance
- inView
- JavaScript Game: Obstakl
- Thin Table Pagination: A new addition to my JavaScript repository
All JavaScript Topics ⟶
JavaScript Carousels
A selection of multi-card, JavaScript-powered carousels for modern browsers.
JavaScript Sliders
A selection of JavaScript-powered sliders for modern browsers. Examples included!
JavaScript Time & Date
A collection of time and date related JavaScript examples and how-to’s.
JavaScript Pagination
Various JavaScript pagination techniques, examples, breakdowns, JSON datasets and more.
JavaScript Arrays & Objects
JavaScript array manipulation for various scenarios, such as sorting, mapping, ordering and more.
JavaScript Canvas
A Canvas playground for all kinds of experiments. Drawing, animating, building games.
JavaScript DOM
DOM manipulation, code injection, elements, classes, ID’s, data attributes, nodes, and HTML.
AJAX and Fetching Data
Fetch data, send GET or POST requests, translate JSON responses into parsable data and more.
Methods, Events, and Scopes
this, closures, global and local scopes and other tricky bits.
Vanilla JavaScript Repository ⟶
A Repository of Fine JavaScript Libraries and Components
Best free JavaScript & CSS libraries for modern web design.
All scripts and libraries have been created in-house, either as client work or simply as a demo. Feel free to use and improve upon any of them.
Thin Select
A custom <select> element with vanilla JavaScript and CSS. Drop your <select> elements inside a <div class="thin-select"></div> element and call it a day.
RoarJS
A responsive, customizable, accessible, zero-dependency, vanilla JavaScript alert/confirm replacement. It automatically centers itself on the page and looks great on any device.
Draggable Carousel
A zero-dependency, vanilla JavaScript draggable and horizontally scrollable carousel.
Stackgrid
A lightweight, easy to implement and fully responsive vanilla JavaScript Masonry grid. As the screen width changes, the grid automatically adjusts the size and position of the cards to create a seamless and visually appealing layout.
DragonflyJS
A tiny vanilla JavaScript library that enables drag and drop functionality with zero dependencies. By implementing this library, a user is able to drag and drop elements and reorder them.
Minimal Slider
A minimal responsive JavaScript slider with CSS transitions, autoplay, infinite slides and wrap-around functionality.
inView
A tiny, tiny vanilla JavaScript lazy loading script that loads images based on screen visibility. Did I say tiny?
Price Range Slider
All JavaScript range sliders are hacks or workarounds. Because there’s no native HTML element for a range slider (only a single value slider), there are lots of libraries and solutions out there.
Mine is the simplest 🤨 and the most fit for my purpose. Feel free to borrow it and improve upon it.
Thin UI
Thin UI is an opinionated, lightweight UI framework consisting of a Flex-powered column grid and a list of basic components, such as form fields and buttons. Built using a functional CSS approach, which means you get exactly what you ask for, without any hidden surprises. The resulting file size is far smaller than a traditional CSS framework.
Thin Table Pagination
This is a JavaScript script that adds pagination functionality to HTML tables. Specifically, the script allows users to display only a certain number of rows per page – by dividing the table rows into pages – and navigate between pages using a set of page navigation links.
Enlageable Images
This script creates a fake lightbox effect to any image, allowing it to become enlargeable on click. It’s a good alternative to any lightbox plugin, or when an <a> element is not desirable.
Implementing Custom Tooltips with Vanilla JavaScript
The following script replaces the native browser tooltip with a custom-styled tooltip that appears when hovering over elements with the class hasTooltip. See the Pen JavaScript Title Tooltip by Ciprian (@ciprian) on…
Enhancing <select> Dropdowns: Removing Duplicates and Sorting Options with Vanilla JavaScript
When working with <select> dropdowns in HTML, it’s common to encounter scenarios where you need to remove duplicate options or sort them alphabetically. Removing Duplicate <option> Elements Duplicate options in a dropdown…
Creating an Autocomplete Search Feature Using Vanilla JavaScript
Autocomplete search is a powerful feature often used in search fields to provide real-time suggestions as users type. We’ll build a simple input field that sends user input via an AJAX request…
Sorting and Ordering Elements Based on Data Attributes with Vanilla JavaScript
Sorting elements on a webpage can be a critical feature when you need to reorder content dynamically. Whether it’s based on custom order parameters or alphabetically, you can achieve this with vanilla…
Sort Elements Based on Data Attributes with Vanilla JavaScript
In a recent project, I was tasked with sorting a large list of elements dynamically based on multiple data attributes. Below, I’ll show you how to achieve this using just data attributes…
Trigger an Event When User Reaches the Bottom of the Page
In a previous project, a client requested an action to be performed when the user scrolled to the bottom of the page or reached the last element in a list. Here’s how…
Generate a Password Using Vanilla JavaScript
Enforcing strong passwords can be challenging, but by providing users with an automated password generation feature, you can enhance both security and user experience. HTML Structure Note: The input type is set…
Equal Height for All Elements Using Vanilla JavaScript
In my ImagePress plugin, we needed to ensure that all boxes have the same height after they have been loaded. Given the following DOM structure: I used the following function: This function…
Ping a Remote PHP File and Store Data in a MySQL Database with JavaScript
Recently, I needed to store details in a remote database using JavaScript. The straightforward approach was to send a GET request to a PHP file on the server. PHP Script The PHP…
How to Measure Page Loading Time with JavaScript
This approach demonstrates how to measure the loading time from the moment a user clicks on a link until the destination page fully loads. It’s particularly useful for tracking the performance of…
Dropdown Autocomplete with contenteditable Fields
Autocomplete for contenteditable Fields Using Vanilla JavaScript If you’ve ever needed to implement autocomplete functionality in a contenteditable field or display a dropdown of possible values, you’re in luck. Previously, I achieved…
Calculating Mean, Median, and Mode in JavaScript
When dealing with statistics, three key measures often come into play — mean, median, and mode. These statistical metrics help us understand data distributions, offering insights into the central tendencies of a…
How to Add Voice Search Capability to Your WordPress Site
How to Add Voice Search to Your WordPress Site Ever wanted to offer voice search functionality on your WordPress site? If you’ve used voice assistants like Siri, Google, or Cortana, you’re familiar…
Animated JavaScript Counter-Up with the Intersection Observer API
An animated counter is a more engaging way to present this information, as it gradually increases the value of the number from zero to its final value. In this tutorial, we will…
How to Build a Vertical Off-Canvas Menu Bar Using JavaScript and CSS
In my work, coming up with fresh navigation ideas and creating an intuitive and efficient navigation system is essential for enhancing user experience. One solution that stands out is the vertical off-canvas…
How to Build a Double Off-Canvas Menu Using JavaScript
Creating a double off-canvas menu can greatly enhance the user experience by providing accessible navigation options without occupying valuable screen space. This article will guide you through how I built a double…
Simplifying Conditional Statements in JavaScript with the && Operator
JavaScript provides several ways to handle conditional logic. One powerful method is the logical AND (&&) operator. This tutorial will show you how to use the && operator and avoid unnecessary if/else…
Grouping Arrays in JavaScript with Object.groupBy() and Map.groupBy()
In JavaScript, there often arises a need to group array elements based on a certain property. Prior to ES2024, this involved custom functions or using libraries like Lodash. However, ES2024 introduced a…
inView
Loading Images Based on Screen Visibility Lazy loading images is a technique that defers the loading of non-critical resources (such as images) until they are needed. This approach can significantly improve page…
Thin Select — Custom JavaScript Dropdown Element
Let’s create a custom <select> element using vanilla JavaScript and CSS. Thin Select provides a sleek and minimalistic design for <select> dropdowns. Here is what we’ll build: See the Pen Thin Select…
How to Create a JavaScript Spinner with Phenakistoscope Effect
In this tutorial, you will learn how to create a JavaScript spinner that mimics the effect of a Phenakistoscope, an early animation device that creates the illusion of motion by spinning images…
How to Lazy Load Google Map Iframe Embed in WordPress
If you embed a Google Map iframe on your WordPress website, you may notice an increase in the total webpage size and a slowdown in your website’s loading speed. This can be…
JavaScript Game: Obstakl
Obstakl is a game where the player needs to avoid moving obstacles, by controlling the main character using the mouse. See the Pen Obstakl – JavaScript Game by Ciprian (@ciprian) on CodePen.…
JavaScript Marquee: A collection of scrolling text snippets
I have started to consider adding scrolling text into my design process. I started by using a CSS-only approach. The principle for the CSS infinite scrolling process is to have a specific…