SyntaxStudy
Sign Up
jQuery Beginner 3 min read

Toggle Text and State

Toggle Patterns

Toggle text, icons, and aria states together to create accessible show/hide and like/unlike buttons.

Example
// Like button toggle
$(document).on("click", ".like-btn", function() {
  const $btn = $(this);
  const liked = $btn.hasClass("liked");
  $btn.toggleClass("liked btn-danger btn-outline-secondary")
      .find(".label").text(liked ? "Like" : "Unlike");
  $btn.find(".bi").toggleClass("bi-heart bi-heart-fill");
  $btn.attr("aria-pressed", !liked);
  const $count = $btn.find(".count");
  $count.text(parseInt($count.text()) + (liked ? -1 : 1));
  $.post("/api/posts/" + $btn.data("id") + "/like", { liked: !liked });
});
Pro Tip

Update aria-pressed on toggle buttons — screen readers announce the pressed/not-pressed state.