Code library

Free snippets & functions

Copy, adapt and use them in your own projects.

fetch('/api/items')
  .then(function (response) { return response.json(); })
  .then(function (data) { console.log(data); });

AJAX asks the server for data without reloading the page. fetch returns a promise.

jQuery · Clone a hidden templateBeginner
$('#add-row').on('click', function () {
  const $row = $('#row-template').clone().removeAttr('id').removeClass('d-none').show();
  $row.find('input').val('');
  $('#rows').append($row);
});

$('#rows').on('click', '.remove-row', function () {
  $(this).closest('.row-item').remove();
});

Keep one hidden row as the pattern and clone it every time the user clicks Add.

jQuery · Read more / read lessBeginner
$('.more-text').each(function () {
  const $p = $(this);
  const full = $p.text().trim();
  const short = full.slice(0, 80) + '…';

  if (full.length <= 80) return;
  $p.text(short);

  $('<a href="#" class="more-link">Read more</a>').insertAfter($p).on('click', function (e) {
    e.preventDefault();
    const expanded = $(this).data('open');
    $p.text(expanded ? short : full);
    $(this).text(expanded ? 'Read more' : 'Read less').data('open', !expanded);
  });
});

Show a short version of long text with a button to expand it.

jQuery · Highlight table rowsBeginner
$('table.data tbody tr:even').addClass('even');
$('table.data tbody tr:odd').addClass('odd');

$('table.data tbody tr').hover(
  function () { $(this).addClass('hover'); },
  function () { $(this).removeClass('hover'); }
);

$('table.data tbody').on('click', 'tr', function () {
  $(this).toggleClass('selected');
});

Zebra stripes and a hover row, with just a few lines.

jQuery · A back-to-top buttonBeginner
const $top = $('#to-top').hide();

$(window).on('scroll', function () {
  $top.toggle($(this).scrollTop() > 300);
});

$top.on('click', function () {
  $('html, body').animate({ scrollTop: 0 }, 400);
});

Show the button after the user scrolls down, and scroll smoothly when it is clicked.

jQuery · A simple accordionBeginner
$('.acc-head').on('click', function () {
  const $panel = $(this).next('.acc-body');

  $('.acc-body').not($panel).slideUp(200);
  $panel.slideToggle(200);
  $(this).toggleClass('open').siblings('.acc-head').removeClass('open');
});

Click a heading to open its panel and close the others.

jQuery · A live character counterBeginner
const max = 140;

$('#bio').on('input', function () {
  const left = max - $(this).val().length;
  $('#left').text(left).toggleClass('over', left < 0);
});

Show how many characters are left while the user types.

const $items = $('#list li');

$items.first().addClass('first');
$items.last().addClass('last');
$items.eq(1).addClass('second');          // zero-based
$items.filter('.done').hide();            // keep only those matching
$items.not('.done').css('font-weight', 'bold');
$items.filter(function () { return $(this).text().length > 3; }).addClass('long');

Narrow down a set of elements.

jQuery · Move around the DOMBeginner
const $btn = $('.edit');

$btn.closest('tr');                 // nearest ancestor row
$btn.parent();                      // direct parent
$('#menu').find('a');               // all links inside
$('#menu li').first().next();       // second item
$('.active').siblings();            // other items next to it
$('.child').parents('.card');       // all matching ancestors

const rowTitle = $btn.closest('tr').find('.title').text();

Start from one element and walk to the ones you need.

jQuery · animate(): custom animationBeginner
$('#box').animate({ left: '200px', opacity: 0.5, height: '+=50' }, 600, function () {
  console.log('finished');
});

$('html, body').animate({ scrollTop: $('#section').offset().top - 70 }, 500);

$('#box').stop(true).animate({ width: 300 }, 200);     // stop the running one first

Animate numeric CSS values. For anything fancy CSS transitions are smoother.

jQuery · Dropdown change eventBeginner
$('#country').on('change', function () {
  const value = $(this).val();                          // 'pk'
  const label = $(this).find('option:selected').text(); // 'Pakistan'
  $('#out').text(label + ' (' + value + ')');
});

$('#country').val('pk').trigger('change');              // set it from code

Read the chosen value and the visible text of the selected option.

jQuery · Checkboxes and radio buttonsBeginner
$('#select-all').on('change', function () {
  $('.row-check').prop('checked', this.checked);
});

$('.row-check').on('change', function () {
  const all = $('.row-check').length === $('.row-check:checked').length;
  $('#select-all').prop('checked', all);
});

const ids = $('.row-check:checked').map(function () { return this.value; }).get();   // ['1', '3']
const gender = $('input[name="gender"]:checked').val();

Use :checked and prop('checked'). Select-all is a classic.

jQuery · Handle a form submitBeginner
$('#contact').on('submit', function (e) {
  e.preventDefault();

  const name = $('#name').val().trim();
  if (name === '') {
    $('#error').text('Please enter your name').show();
    return;
  }
  $('#error').hide();
  console.log('send', $(this).serialize());     // name=Ali&email=...
});

Stop the normal submit, check the fields and then decide what to do.

jQuery · Events for elements added laterBeginner
// does NOT work for rows added later:  $('.remove').on('click', ...)

$('#table').on('click', '.remove', function () {
  $(this).closest('tr').remove();
});

$('#table').append('<tr><td><button class="remove">x</button></td></tr>');   // works too

Attach the handler to a parent that always exists, and give the child selector as the second argument.

jQuery · Hover effectsBeginner
$('.card').hover(
  function () { $(this).addClass('hovered'); },       // mouse enters
  function () { $(this).removeClass('hovered'); }     // mouse leaves
);

// or the same with on():
$('.thumb').on('mouseenter mouseleave', function (e) {
  $(this).toggleClass('zoom', e.type === 'mouseenter');
});

Pass one function to run on enter and one on leave.

jQuery · Loop with each()Beginner
let total = 0;

$('.price').each(function (index) {
  const value = parseFloat($(this).text());
  total += value;
  $(this).text('Rs ' + value.toFixed(2));
});

$.each(['a', 'b'], function (i, item) {
  console.log(i, item);
});

Run code for every matched element. this is the DOM element, so wrap it in $().

jQuery · Remove or empty elementsBeginner
$('.old').remove();                    // delete all with class old
$('#results').empty();                 // keep the box, clear its content

$('.delete').on('click', function () {
  $(this).closest('tr').remove();      // delete the row this button is in
});

remove() deletes the element. empty() only clears what is inside it.

jQuery · Add new elementsBeginner
const $li = $('<li>', { text: 'New item', class: 'item' });   // creates the element safely

$('#list').append($li);                // at the end, inside
$('#list').prepend('<li>First</li>');  // at the start, inside
$('#title').after('<p>After the title</p>');
$('#title').before('<hr>');

Four ways to put new content inside or next to an element.

jQuery · Read and set CSSBeginner
$('#box').css('color', 'green');

$('#box').css({
  'background-color': '#eef',
  padding: '12px',
  borderRadius: '8px',
});

const color = $('#box').css('color');
const width = $('#box').width();           // number, no 'px'

css() sets inline styles. width(), height() and offset() give numbers.

jQuery · attr(), prop() and data()Beginner
$('a').attr('target', '_blank');                 // set attribute
const href = $('#link').attr('href');            // read attribute
$('#link').removeAttr('title');

const checked = $('#agree').prop('checked');     // true / false (use prop for checkboxes)
$('#send').prop('disabled', !checked);

const id = $('#row').data('id');                 // data-id="42" -> 42 (a number)
$('#row').data('state', 'open');                 // stored in memory, not in the HTML

attr reads HTML attributes, prop reads the live state (checked, disabled), data reads data-* values.

jQuery · Fade and slide effectsBeginner
$('#notice').fadeIn(300);
$('#notice').delay(3000).fadeOut(300, function () {
  $(this).remove();                    // runs when the fade ends
});

$('.faq-q').on('click', function () {
  $(this).next('.faq-a').slideToggle(200);
});

Built-in effects with an optional callback when they finish.

jQuery · show, hide and toggleBeginner
$('#help').hide();
$('#help-link').on('click', function (e) {
  e.preventDefault();
  $('#help').toggle(200);          // 200 ms
});

$('.error').show();
const visible = $('#help').is(':visible');

Quick visibility changes. Pass a speed for a fade-like effect.

$('#card').addClass('active');
$('#card').removeClass('hidden');
$('#menu-btn').on('click', function () {
  $('#menu').toggleClass('open');
});

const isActive = $('#card').hasClass('active');
$('#card').toggleClass('big', true);        // force on (false = force off)

Change how things look by changing classes, not inline styles.

jQuery · text(), html() and val()Beginner
$('#title').text('Hello');                 // set text (safe)
const t = $('#title').text();              // read text

$('#box').html('<b>Bold</b>');             // set HTML (only for your own markup)

$('#name').val('Ali');                     // set input value
const name = $('#name').val();             // read input value

With no argument they read, with an argument they write. Use text() for user content, never html().

jQuery · Handle a clickBeginner
$('#save').on('click', function (e) {
  e.preventDefault();
  $(this).text('Saved').prop('disabled', true);
});

$('a.external').on('click', function () {
  console.log('going to', $(this).attr('href'));
});

Use on() for every event. Return false or call preventDefault() to stop a link from jumping.

jQuery · The selectors you use every dayBeginner
$('#menu');                  // by id
$('.item');                  // by class
$('a');                      // by tag
$('ul li:first-child');      // CSS pseudo selectors
$('input[type="email"]');    // attribute
$('#list > li.active');      // child + class
$('h1, h2, h3');             // several at once

const count = $('.item').length;       // how many were found?

jQuery uses CSS selectors, so what you know from CSS works here.

jQuery · Run code when the page is readyBeginner
$(function () {
  // same as $(document).ready(function () { ... });
  console.log('DOM is ready');
  $('#msg').text('Page loaded');
});

Put your code inside ready() so the elements exist before you use them. Scripts at the end of do not need it.

JavaScript · Ask before a dangerous actionBeginner
document.querySelectorAll('[data-confirm]').forEach((el) => {
  el.addEventListener('click', (e) => {
    if (!confirm(el.dataset.confirm)) {
      e.preventDefault();                  // cancel the link or form
    }
  });
});

// <a href="/delete?id=5" data-confirm="Delete this item?">Delete</a>

Confirm destructive clicks. Still check the permission on the server too.

const input = document.querySelector('#q');
let timer;

input.addEventListener('input', () => {
  clearTimeout(timer);
  timer = setTimeout(() => {
    console.log('search for', input.value.trim());
  }, 300);
});

Wait a short moment after each key press, so a search runs once and not on every letter.

JavaScript · Random numbers and shufflingBeginner
const randInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;   // inclusive

function shuffle(array) {
  const a = [...array];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

const dice = randInt(1, 6);
const pick = ['a', 'b', 'c'][randInt(0, 2)];
const token = crypto.getRandomValues(new Uint32Array(1))[0];     // secure value

Math.random() is fine for games and layout. Use crypto for anything secret.