SyntaxStudy
Sign Up
jQuery Toggle Buttons with .data()
jQuery Beginner 3 min read

Toggle Buttons with .data()

Toggle Button State

Track whether a button is in "on" or "off" state using .data() and update its appearance accordingly.

Example
$(".toggle-btn").each(function() {
  $(this).data("on", false);
});

$(document).on("click", ".toggle-btn", function() {
  const on = !$(this).data("on");
  $(this).data("on", on)
    .toggleClass("btn-primary", on)
    .toggleClass("btn-outline-secondary", !on)
    .text(on ? "On" : "Off");
});
Pro Tip

Storing state in .data() keeps your logic clean and avoids DOM inspection to determine state.