Search code examples
javascriptjqueryangularjsangularjs-components

How to track DOM element's class attribute changes and apply same on some element


I have a angularjs component, In the component I have following HTML

<div id="panel" class="hide-div">
  <div id="viewPort" class="hide-div">
     ...
  </div>
</div>

There is a third party javascript/jquery library, I don't have control over third party library, third-party library removes the class hide-div from the viewPort on some server-side event.
hide-div class hides the element.

Now my requirement is to remove the hide-div class from panel, when it is removed from viewPort. In short if viewPort is hidden then panel should be hidden and if viewPort is visible then panel should be visible too.


Solution

  • If possible, hook into that other library to get a proactive notification from it when it shows/hides that div.

    If you can't do that, you can use a mutation observer to watch for changes to the attributes on the element, and then show/hide your other element depending on whether that element has the relevant class.

    Example:

    // Your code
    var observer = new MutationObserver(function() {
        var source = $("#source");
        var target = $("#target");
        target.toggleClass("hide-div", source.hasClass("hide-div"));
    });
    observer.observe($("#source")[0], {attributes: true});
    
    // This code emulates the library that you don't control
    var handle = setInterval(function() {
      $("#source").toggleClass("hide-div");
    }, 800);
    $("#btn-stop").on("click", function() {
      clearInterval(handle);
    });
    .hide-div {
      display: none;
    }
    <button id="btn-stop">Stop</button>
    
    <div id="source">This is the source element that the library changes</div>
    <div id="target">This is the target element that we update when the source element changes</div>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>