davinci davinci - 24 days ago 10
HTML Question

jQuery.appear simply not working

Can anyone see why this html code doesn’t work.

It should show an alert when the image gets visible and again when it gets invisible for the user.

It doesn't work with local libraries either.

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/morr/jquery.appear/master/jquery.appear.js"></script>

<script>
var intervals = [];
$("[id^=light]").on('appear', function(event, $all_appeared_elements) {
alert("appeared");
});

$("[id^=light]").on('disappear', function(event, $all_disappeared_elements) {
alert("disappeared");
});

</script>

<br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/62/Incandescent_light_bulb.svg/200px-Incandescent_light_bulb.svg.png" align="center" id="LichtStatus" style="height:10vh">

</body>
</html>

Answer

Put your code inside document ready to make sure the DOM is loaded. Also specify the element as @Louys Patrice Bessette mentioned. I added appear call which @Deep got right.

 <script>    
 $(function(){
 var intervals = [];
  $("img[id^='Licht']").appear();
  $("img[id^='Licht']").on('appear', function(event, $all_appeared_elements) {
      alert("appeared");
  });

  $("img[id^='Licht']").on('disappear', function(event,$all_disappeared_elements) {
      alert("disappeared");
  });
});
</script> 

I saw that the alerts show twice with the above code. After I change the code as below, I noticed that the alerts don't show twice.

$(document.body).on('appear',"img[id^='Licht']", function(event, $all_appeared_elements) {
      alert("appeared");
  });

  $(document.body).on('disappear',"img[id^='Licht']", function(event, $all_appeared_elements) {
      alert("disappeared");
  });