JavaScript Snippets & Tutorials
JavaScript snippets and short tutorials for the browser: DOM manipulation, string and number tricks, and event handling.
All examples use plain JavaScript (vanilla JS). If you use jQuery for the same tasks, see our jQuery section. Code is written for modern browsers; we avoid deprecated APIs and keep polyfills out of the snippets so you can read and adapt them quickly.
Rotate an image with JavaScript
let degrees = 0;
function rotateImage() {
degrees += 30;
document.getElementById("myImage").style.transform = "rotate(" + degrees + "deg)";
}
Attach rotateImage to a button’s click event. Each click adds 30° to the current rotation. Use transform-origin in CSS if you need to change the pivot point.
Round a number to the nearest 10
function roundToNearest10(num) {
return Math.round(num / 10) * 10;
}
roundToNearest10(37); // 40
roundToNearest10(33); // 30
Divide by 10, round with Math.round(), then multiply by 10. For nearest 100 use / 100 and * 100.
Remove vowels from a string
function removeVowels(str) {
return str.replace(/[aeiouAEIOU]/g, "");
}
removeVowels("hello world"); // "hll wrld"
The regex /[aeiouAEIOU]/g matches any vowel (add more characters to the set if you need a different locale). replace with an empty string removes them.
Add trailing zeros to a number (display)
function toFixedWidth(num, length) {
return num.toString().padStart(length, "0");
}
toFixedWidth(7, 3); // "007"
toFixedWidth(42, 4); // "0042"
padStart(length, "0") pads the string to the left. For decimal places use num.toFixed(2) to get a string like "3.14".
More JavaScript topics
See also: jQuery, Learn to Code, and Code Snippets.