Trigger on Object becomes visible

This will trigger a click on the box when the box is vertically centered in the window. The trigger just goes off once.

by Ben Clayton

HTML

Scroll to view box
<div class=box></div>

CSS

.box {
  border: red 1px solid;
  width: 100px;
  height: 100px;
  margin-top: 600px;
  margin-bottom: 600px;
}

JavaScript

$(document).on('click', '.box', function(e) {
  $(e.target).css("background-color", "red");
});
var triggered = 0;
$(window).scroll(function() {
  console.log("Window scroll top: ", $(window).scrollTop());
  console.log("Window height : ", $(window).height());
  console.log("Object top: ", $(".box").offset().top);
  console.log("Object heigth: ", $(".box").height());

  var $box = $(".box");

  if (!triggered && $(window).scrollTop() > ($box.offset().top - ($(window).height() - $box.height()) / 2)) {
    $box.trigger('click');
    triggered = 1;
  }

});