Skip to content

Article

25 Must-Have jQuery Code Snippets for Faster Web Development

jQuery remains one of the most popular JavaScript libraries, making DOM manipulation, event handling, and AJAX requests incredibly simple. Whether you’re maintaining legacy code or starting a new project, these 25 snippets will save you time and effort. Each snippet is battle-tested and ready to use in production.

Hardik Desai28 Nov 20256 min read

jQuery Snippets

DOM Ready & Initialization#

1. Document Ready Shortcut#

js
$(function () {
  console.log("Ready!");
});

Why use it: The shortest way to wait for DOM ready. Equivalent to $(document).ready() but more concise.

Use case: Initialize your app, bind events, or start any DOM-dependent code.

2. Smooth Scroll to Element#

js
$("html, body").animate(
  {
    scrollTop: $("#target").offset().top,
  },
  600
);

Enhanced version with offset:

js
function smoothScrollTo(target, offset = 0) {
  $("html, body").animate(
    {
      scrollTop: $(target).offset().top - offset,
    },
    600
  );
}

// Usage: smoothScrollTo('#section', 80); // 80px offset for fixed header

Use case: Smooth navigation for single-page applications, anchor links, or “back to top” functionality.

3. Scroll to Top Button#

js
$("#backTop").click(() => $("html, body").animate({ scrollTop: 0 }, 500));

Complete implementation:

js
// Show/hide button based on scroll position
$(window).scroll(function () {
  if ($(this).scrollTop() > 300) {
    $("#backTop").fadeIn();
  } else {
    $("#backTop").fadeOut();
  }
});

4. Detect Scroll Position#

js
$(window).on("scroll", function () {
  const y = $(this).scrollTop();

  // Example: Change header on scroll
  if (y > 100) {
    $(".header").addClass("scrolled");
  } else {
    $(".header").removeClass("scrolled");
  }
});

Use case: Sticky headers, parallax effects, or loading content on scroll.

Utility Functions#

function code preview

5. Copy to Clipboard#

js
function copyText(text) {
  navigator.clipboard
    .writeText(text)
    .then(() => {
      console.log("Copied to clipboard");
    })
    .catch((err) => {
      console.error("Copy failed:", err);
    });
}

// jQuery integration
$(".copy-btn").click(function () {
  const text = $(this).data("copy-text");
  copyText(text);
});

Use case: Copy coupon codes, share links, or code snippets.`

6. Check if Element Exists#

js
if ($("#element").length) {
  // Element exists
  console.log("Element found");
}

// More specific checks
if ($(".modal").is(":visible")) {
  // Modal is visible
}

Use case: Conditional code execution, avoiding errors when elements don’t exist.

7. Debounce Function#

js
const debounce = (fn, delay) => {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
};

// Usage with search input
$("#search").on(
  "input",
  debounce(function () {
    const query = $(this).val();
    // Perform search
  }, 300)
);

Use case: Search inputs, resize handlers, scroll events to improve performance.

Interactive Elements#

8. Toggle Class on Click#

js
$(".btn").on("click", function () {
  $(this).toggleClass("active");
});

// Advanced: Toggle between multiple states
$(".theme-btn").click(function () {
  $("body").toggleClass("dark-theme light-theme");
});

9. Highlight Input on Focus#

js
$("input").on("focus blur", function (e) {
  $(this).toggleClass("highlight", e.type === "focus");
});

// Alternative with CSS classes
$("input")
  .on("focus", function () {
    $(this).addClass("focused");
  })
  .on("blur", function () {
    $(this).removeClass("focused");
  });

Form Handling#

form handling image

10. Get/Set Input Value#

js
// Get value
const name = $("#name").val();

// Set value
$("#name").val("Hardik");

// Clear all inputs in form
$("#myForm input").val("");

// Get all form data as object
function getFormData(formId) {
  const data = {};
  $(formId + " input, " + formId + " select, " + formId + " textarea").each(
    function () {
      data[this.name] = $(this).val();
    }
  );
  return data;
}

11. Check if Checkbox is Checked#

js
if ($("#agree").is(":checked")) {
  console.log("Checkbox is checked");
}

// Get all checked checkboxes
const checkedItems = $('input[type="checkbox"]:checked')
  .map(function () {
    return this.value;
  })
  .get();

// Toggle all checkboxes
$("#selectAll").change(function () {
  $(".item-checkbox").prop("checked", this.checked);
});

12. Get Selected Option Text#

js
// Get selected option text
const selectedText = $("#city option:selected").text();

// Get selected value
const selectedValue = $("#city").val();

// Populate dropdown dynamically
function populateSelect(selectId, options) {
  const $select = $(selectId);
  $select.empty();
  options.forEach((option) => {
    $select.append(`<option value="${option.value}">${option.text}</option>`);
  });
}

13. Count Characters in Textarea#

js
$("#text").on("input", function () {
  const count = this.value.length;
  const maxLength = $(this).attr("maxlength") || 500;

  $("#count").text(`${count}/${maxLength}`);

  // Visual feedback when approaching limit
  if (count > maxLength * 0.9) {
    $("#count").addClass("warning");
  } else {
    $("#count").removeClass("warning");
  }
});

14. Toggle Password Visibility`#

js
$("#togglePass").click(function () {
  const $password = $("#password");
  const $icon = $(this);

  if ($password.attr("type") === "password") {
    $password.attr("type", "text");
    $icon.text("🙈"); // or use CSS classes for icons
  } else {
    $password.attr("type", "password");
    $icon.text("👁️");
  }
});

Animations & Effects#

animations and effect

15. Fade In / Fade Out#

js
$(".box").fadeIn(400);
$(".box").fadeOut(400);

// Fade toggle
$(".toggle-btn").click(function () {
  $(".box").fadeToggle(400);
});

// Chain animations
$(".element").fadeOut(200).delay(100).fadeIn(300);

16. Slide Toggle#

js
$(".toggle-btn").click(function () {
  $(".panel").slideToggle(300);
});

// Accordion effect
$(".accordion-header").click(function () {
  const $panel = $(this).next(".accordion-panel");
  $(".accordion-panel").not($panel).slideUp();
  $panel.slideToggle();
});

AJAX & Data Loading#

data

17. AJAX GET Request#

js
$.get("/api/data", function (response) {
  console.log(response);
}).fail(function (xhr, status, error) {
  console.error("Error:", error);
});

// Modern Promise-based approach
$.get("/api/users")
  .done((data) => {
    // Handle success
    displayUsers(data);
  })
  .fail((xhr) => {
    // Handle error
    showError("Failed to load users");
  });

18. AJAX POST Request#

js
$.post("/api/save", { name: "Hardik", email: "hardik@example.com" })
  .done(function (response) {
    console.log("Saved successfully");
  })
  .fail(function (xhr) {
    console.error("Save failed");
  });

// With JSON content type
$.ajax({
  url: "/api/users",
  method: "POST",
  contentType: "application/json",
  data: JSON.stringify({ name: "Hardik" }),
  success: function (response) {
    console.log("User created");
  },
});

Event Handling#

event handling

19. Detect Enter Key#

js
$(document).keypress(function (e) {
  if (e.which === 13) {
    console.log("Enter pressed");
  }
});

// For specific input
$("#searchInput").keypress(function (e) {
  if (e.which === 13) {
    performSearch($(this).val());
  }
});

// Handle multiple keys
$(document).keydown(function (e) {
  switch (e.which) {
    case 27: // ESC
      closeModal();
      break;
    case 13: // Enter
      submitForm();
      break;
  }
});

20. Disable Right Click#

js
$(document).on("contextmenu", function (e) {
  e.preventDefault();
  return false;
});

// Disable on specific elements only
$(".protected-content").on("contextmenu", function (e) {
  e.preventDefault();
});

DOM Manipulation#

21. Clone an Element#

js
// Basic clone
$(".item:first").clone().appendTo(".list");

// Clone with event handlers
$(".item:first").clone(true).appendTo(".list");

// Clone and modify
const $newItem = $(".template")
  .clone()
  .removeClass("template")
  .addClass("active")
  .find(".title")
  .text("New Item")
  .end();

22. Remove Element#

js
// Remove element
$(".target").remove();

// Remove but keep data and events
$(".target").detach();

// Empty content but keep element
$(".container").empty();

// Remove specific children
$(".list").children(".item.old").remove();

Utility & Helpers#

23. Get Window Width/Height#

js
const windowWidth = $(window).width();
const windowHeight = $(window).height();

// Responsive breakpoint detection
function checkBreakpoint() {
  const width = $(window).width();
  if (width < 768) {
    return "mobile";
  } else if (width < 1024) {
    return "tablet";
  } else {
    return "desktop";
  }
}

$(window).resize(
  debounce(function () {
    const breakpoint = checkBreakpoint();
    $("body").attr("data-breakpoint", breakpoint);
  }, 250)
);

24. Simple Tooltip#

js
$("[data-tooltip]")
  .hover(
    function () {
      const tooltip = $(this).data("tooltip");
      $('<div class="tooltip">' + tooltip + "</div>")
        .appendTo("body")
        .fadeIn();
    },
    function () {
      $(".tooltip").remove();
    }
  )
  .mousemove(function (e) {
    $(".tooltip").css({
      top: e.pageY + 10,
      left: e.pageX + 10,
    });
  });

25. Lazy Load Images#

js
// Basic lazy loading
$("img[data-src]").each(function () {
  $(this).attr("src", $(this).data("src"));
});

// Intersection Observer approach (modern)
function lazyLoadImages() {
  const imageObserver = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        const img = entry.target;
        img.src = img.dataset.src;
        img.classList.remove("lazy");
        imageObserver.unobserve(img);
      }
    });
  });

  $("img[data-src]").each(function () {
    imageObserver.observe(this);
  });
}

Bonus Snippets#

Form Validation Helper#

js
function validateForm(formId) {
  let isValid = true;

  $(formId + " [required]").each(function () {
    const $field = $(this);
    if (!$field.val().trim()) {
      $field.addClass("error");
      isValid = false;
    } else {
      $field.removeClass("error");
    }
  });

  return isValid;
}

Loading State Management#

js
function setLoadingState($element, isLoading) {
  if (isLoading) {
    $element.addClass("loading").prop("disabled", true);
  } else {
    $element.removeClass("loading").prop("disabled", false);
  }
}

// Usage
setLoadingState($("#submitBtn"), true);

Best Practices & Tips#

Performance: Always cache jQuery selectors when used multiple times

js
const $window = $(window); const $document = $(document);

Event Delegation: Use .on() for dynamically added elements

js
$(document).on("click", ".dynamic-button", function () {   // Handler for dynamically added buttons });

Chaining: Take advantage of jQuery’s chainable methods

js
$("#element").addClass("active").fadeIn(300).delay(1000).fadeOut(300);

Modern Alternatives: Consider using vanilla JavaScript for simple operations

js
// jQuery 
$("#element").addClass("active"); 
 
// Vanilla JS 
document.getElementById("element").classList.add("active");

Conclusion#

These 25 jQuery snippets cover the most common tasks you’ll encounter in web development. While modern frameworks have changed how we build applications, jQuery remains valuable for rapid prototyping, legacy maintenance, and simple DOM manipulation tasks.


Remember to:

  • Always check if elements exist before manipulating them
  • Use event delegation for dynamic content
  • Consider performance implications of frequent DOM queries
  • Test snippets in your specific environment before production use

Bookmark this collection and adapt these snippets to your specific needs. Happy coding!


If you enjoyed this post or have any feedback, feel free to connect with me:

  • 💼 LinkedIn — Let’s network and share ideas!
  • 👨‍💻 GitHub — Check out more of my projects and code examples.

If you enjoyed my content or want to support my writing journey, please take a moment to follow me on Medium. I regularly share insights on JavaScript, modern frontend development, and practical dev tricks you can use in real projects.

🔗 Read the original article on Medium:

https://medium.com/javascript-in-plain-english/25-must-have-jquery-code-snippets-for-faster-web-development-d002471d62ff


❤️ Follow me on Medium for more:

https://medium.com/@dhardik1430

Was this helpful?
Share X LinkedIn

The Build Log

New posts, plugin releases, and the Sanity + Next.js tricks that didn't fit in a blog post. About once a month.

Keep reading#