How to create a toggle button using jQuery

Viewed 106

I am trying to toggle a button using below code.

import $ from "jquery";

$(".clickMe").click(function() {
  $(this).text(function(i, text) {
    return text === "ON" ? "OFF" : "ON";
  })
});

const rootApp = document.getElementById("root");
rootApp.innerHTML = '<button class="clickMe">ON </button>'
1 Answers

You have multiple problem in your code.

  1. Dynamic created markup need delegated event handlers.
  2. You have extra space on button text. You need to trim() text to avoid extra space before proceed.

Example:

$(document).on('click', '.clickMe', function() {
  $(this).text(function(i, text) {
    var txt = text.trim();
    return txt === "ON" ? "OFF" : "ON";
  })
});
const rootApp = document.getElementById("root");
rootApp.innerHTML = '<button class="clickMe">ON </button>'
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="root"></div>

Or only jQuery Version:

const rootApp = $('#root');
var html = `<button class="clickMe">ON </button>`; // Declare your button
rootApp.append(html); // Append your HTML on desire element

$(document).on('click', '.clickMe', function() {
  $(this).text(function(i, text) {
    var txt = text.trim();
    return txt === "ON" ? "OFF" : "ON";
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="root"></div>

Related