Detecting Class Change with JQuery

Change class name on click and detect a change in class using jQuery.

by mozfet

HTML

<link rel="stylesheet" href="https://github.com/Dogfalo/materialize/blob/v1-dev/dist/css/materialize.min.css">
<script src="https://github.com/Dogfalo/materialize/blob/v1-dev/dist/js/materialize.min.js"></script>
<div id="banner-message">
  <p>Hello World</p>
  <button>Change color</button>
  <div class="input-field col s12">
    <select>
      <option value="" disabled selected>Choose your option</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>
    <label>Materialize Select</label>
  </div>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

JavaScript

// on document ready
$(function() {

  // extend jquery with attribute change mutation observer plugin
  (function($) {
    var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver

    $.fn.attrchange = function(callback) {
      if (MutationObserver) {
        var options = {
          subtree: false,
          attributes: true
        }

        var observer = new MutationObserver(
          function(mutations) {
            mutations.forEach(
              function(e) {
                callback.call(e.target, e.attributeName);
              }
            )
          }
        )

        return this.each(
          function() {
            observer.observe(this, options);
          }
        )
      }
    }
  })(jQuery)
  
  // auto initialize all materialize components
  M.AutoInit()

  // find elements
  var banner = $("#banner-message")
  var button = $("button")

  // handle click
  button.on("click", () => {

    // add class
    banner.addClass("alt")
  })

  // on attribute change
  banner.attrchange(attrName => {
    if (attrName == 'class') {
      alert('class changed')
    } else if (attrName == 'id') {
      alert('id changed')
    } else {
      //OTHER ATTR CHANGED
    }
  })
})