1

I have a number of elements on the a page which are hidden by default. Depending on a user behaviour, one might be shown (using jquery's show()). Similar, one might be hidden (using jquery's hide()).

All these elements have the same css class. Is there a way to create a listener for elements with a specific class to see if any of them have changed between hide/show?

Thanks!

David
  • 16,246
  • 34
  • 103
  • 162

2 Answers2

2

You can use :visible or :hidden. More info here https://api.jquery.com/visible-selector/ and here https://api.jquery.com/hidden-selector/

var $foo = $('.foo');

$foo.first().hide();

$('.foo').each(function() {
  console.log($(this).is(":visible"));
  console.log($(this).is(":hidden"));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">foo</div>
<div class="foo">foo</div>
Michael Coker
  • 52,626
  • 5
  • 64
  • 64
  • Unfortunately, that isn't going to 'listen' to when elements with the foo class are changed. I'm trying to trigger some code for every time elements with a particular class are show/hidden. – David Mar 30 '17 at 15:01
  • @David ah, sorry I misunderstood. This question has a couple of options http://stackoverflow.com/questions/2857900/onhide-type-event-in-jquery this guy's plugin looks like it might work https://github.com/hypesystem/showandtell.js – Michael Coker Mar 30 '17 at 15:09
0

To directly answer your question, no there is no built in way, but we can achieve this through custom .on's and .trigger's.

isVisibleList = [];
setInterval(function() {
  for (var i = 0, len = isVisibleList.length; i < len; i++) {
    if (isVisibleList[i].is(":visible") != isVisibleList[i].data("wasVisible")) {
      isVisibleList[i].data("wasVisible", !isVisibleList[i].data("wasVisible"));
      if (isVisibleList[i].is(":visible")) {
        isVisibleList[i].trigger("show");
      } else {
        isVisibleList[i].trigger("hide");
      }
    }
  }
}, 500);

$("#test").hide();
$("#test").data("wasVisible", false);
isVisibleList.push($("#test"));

$("#toggle").click(function() {
  $("#test").toggle();
});

$("#test").on("show", function() {
  console.log("shown");
});

$("#test").on("hide", function() {
  console.log("hidden");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">Test toggle</button>
<div id="test">test</div>
Neil
  • 14,063
  • 3
  • 30
  • 51