Q188813

Change class name on click in jQuery

by jun68ykt

HTML

<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<div id="buttons-area"></div>

<input type="checkbox" class="checkbox" />

CSS

button {
  font-size: 12pt;
  margin: 5px;
}

.checkbox {
  -ms-transform: scale(2); /* IE */
  -moz-transform: scale(2); /* FF */
  -webkit-transform: scale(2); /* Safari and Chrome */
  -o-transform: scale(2); /* Opera */
  transform: scale(2);
  padding: 10px;
  margin: 15px;
}

JavaScript

const buttonHtmlWithRandomName = function() {
    const name = Math.random().toString(36).slice(-8).toUpperCase();
    return `<button data-name="${name}" type="button"><!--空っぽ--></button>`;
};

const setupObserver = function() {
    
    const callback = function(mutationsList, observer) {
      for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            const button = $(mutation.addedNodes[0]);
            button.text(button.data('name'));
        }
      }
    };
    const observer = new MutationObserver(callback);

    const targetNode = document.getElementById('buttons-area');
    
    observer.observe(targetNode, { childList: true });
};


$(function() {

    setupObserver();
    
    const ajaxRequest = function(html) {
        $.ajax({
            type: "POST",
            url: "/echo/html/",
            data: {
                html,
                delay: 1,
            },
            success: function(button) {              
                $('#buttons-area').append(button);
            }
        });
    };


    $('.checkbox').change(function() {
        if ($(this).prop('checked')) {
            const html = buttonHtmlWithRandomName();
            ajaxRequest(html);
        }
    });

});