JavaScript Top Codes
JavaScript Tabs without jQuery
Tabs show one panel of content at a time. You do not need jQuery: a few lines of plain JavaScript are enough.
HTML
<div class="tabs">
<button class="tab-btn active" data-tab="html">HTML</button>
<button class="tab-btn" data-tab="css">CSS</button>
<button class="tab-btn" data-tab="js">JavaScript</button>
</div>
<div id="html" class="tab-panel active">HTML gives the structure.</div>
<div id="css" class="tab-panel">CSS gives the style.</div>
<div id="js" class="tab-panel">JavaScript gives the behaviour.</div>
CSS
.tab-btn { padding: 8px 16px; border: 0; background: #eee; cursor: pointer; }
.tab-btn.active { background: #0073aa; color: #fff; }
.tab-panel { display: none; padding: 12px; border: 1px solid #ddd; }
.tab-panel.active { display: block; }
JavaScript
const buttons = document.querySelectorAll(".tab-btn");
const panels = document.querySelectorAll(".tab-panel");
buttons.forEach(button => {
button.addEventListener("click", () => {
// remove the active class from all
buttons.forEach(b => b.classList.remove("active"));
panels.forEach(p => p.classList.remove("active"));
// add it to the clicked tab and its panel
button.classList.add("active");
document.getElementById(button.dataset.tab).classList.add("active");
});
});
Output in the browser (the page after the CSS tab is clicked):
How it works
- Each button has a
data-tabattribute with the id of its panel. - Only the element with the class
activeis shown (display: block), the others are hidden. - On click, the code removes
activefrom all tabs and panels, and adds it to the chosen ones.
Related: HTML DOM and DOM EventListener.
JavaScript Copy Text to Clipboard
You can copy text to the visitor’s clipboard with the modern Clipboard API. It is used for “Copy code” and “Copy link” buttons.
HTML and JavaScript
<input type="text" id="coupon" value="SAVE20" readonly>
<button id="copyBtn">Copy</button>
<span id="status"></span>
<script>
const input = document.getElementById("coupon");
const status = document.getElementById("status");
document.getElementById("copyBtn").addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(input.value);
status.textContent = "Copied!";
} catch (error) {
status.textContent = "Could not copy";
}
});
</script>
Output in the browser (after clicking Copy):
Copied!
How it works
navigator.clipboard.writeText()returns a promise, so we useawait(see async and await).- It works only on secure pages (https or localhost) and after a user action like a click.
- The
try...catchshows a message if the browser blocks it.
To read text from the clipboard use navigator.clipboard.readText(). The browser asks the visitor for permission first.
JavaScript Debounce Function
When a visitor types in a search box, the input event fires on every key. Calling the server for each letter is wasteful. A debounce function waits until the visitor has stopped typing for a short time, and then runs once.
Debounce function
function debounce(fn, delay = 300) {
let timer;
return function (...args) {
clearTimeout(timer); // cancel the previous call
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
Use it
function search(text) {
console.log("Searching for: " + text);
}
const debouncedSearch = debounce(search, 300);
// fast calls, like fast typing
debouncedSearch("j");
debouncedSearch("ja");
debouncedSearch("jav");
Only the last call runs, 300 ms after it:
Searching for: jav
With a real input box:
input.addEventListener("input", (e) => debouncedSearch(e.target.value));
How it works
- Every call clears the old timer and starts a new one.
- The function runs only when no new call comes for
delaymilliseconds. - The timer is kept in a closure, so each debounced function has its own timer.
If you need to run the function at regular intervals while events keep coming (like scroll), you need a throttle. Read debounce vs throttle.
JavaScript Countdown Timer
A countdown shows the time left until a date, such as a sale end or an event. We use setInterval() to update it every second.
HTML and JavaScript
<p id="countdown"></p>
<script>
const target = new Date("2030-01-01T00:00:00").getTime();
const el = document.getElementById("countdown");
const timer = setInterval(() => {
const diff = target - Date.now();
if (diff <= 0) {
clearInterval(timer);
el.textContent = "Time is over!";
return;
}
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor((diff / (1000 * 60 * 60)) % 24);
const minutes = Math.floor((diff / (1000 * 60)) % 60);
const seconds = Math.floor((diff / 1000) % 60);
el.textContent = `${days}d ${hours}h ${minutes}m ${seconds}s`;
}, 1000);
</script>
Output in the browser (the numbers change every second; this is one example):
1234d 5h 42m 17s
How it works
target - Date.now()is the time left in milliseconds.- We divide by 1000 (seconds), 60 (minutes), 60 (hours) and 24 (days), and use
%to keep only the part that belongs to each unit. - When the time is over,
clearInterval()stops the timer.
Related: JavaScript Date and Callbacks and Promises.
JavaScript Random Number Generator
Math.random() gives a decimal from 0 up to (not including) 1. These small functions turn it into what you usually need.
Random integer between min and max
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 6)); // like a dice
console.log(randomInt(10, 20));
The output is different each time. A sample run:
4
17
Random item from an array
function randomItem(array) {
return array[Math.floor(Math.random() * array.length)];
}
console.log(randomItem(["red", "green", "blue"]));
Shuffle an array (Fisher-Yates)
function shuffle(array) {
const copy = [...array];
for (let i = copy.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
}
console.log(shuffle([1, 2, 3, 4, 5]));
Related: Numbers and Math.