3

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>'
0

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.