1

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.

1 Answers1

0

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>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • don't have control over a library. –  May 16 '18 at 16:54
  • @Govinda - That situation is what the second paragraph above is for, the one starting *"If you can't do that..."* – T.J. Crowder May 16 '18 at 17:04
  • Do you know any other way to do the same. angularjs way? –  May 23 '18 at 11:57
  • @Govinda - The mutation observer part would be the same. The show/hide part would be specific to your exact Angular code. **If** you can't figure out the show/hide part, post a question with a [mcve] in it demonstrating the problem. – T.J. Crowder May 23 '18 at 12:09
  • I tried your solution, it is working fine. But test cases are failing. https://stackoverflow.com/questions/50398703/jasmine-how-to-mock-mutationobserver?noredirect=1#comment87963551_50398703 –  May 23 '18 at 12:10