jQuery new divs won’t animate with $(document).on

So, I had an animation function. It worked. You hover over some squares, they leave a little trail and then fade back:

 $(".square").bind("webkitAnimationEnd mozAnimationEnd animationend", function(){
  $(this).removeClass("squareAnim");  
});

$(".square").hover(function(){
  $(this).addClass("squareAnim");        
});
.squareAnim {
    animation-name: changeColor;
    animation-duration: 4s;
  }

  @keyframes changeColor {
    0% {background-color: rgb(5, 5, 5);}
    25% {background-color: rgba(255, 5, 20);}
    50% {background-color: rgba(20, 5, 255);}
    100% {background-color: rgb(5, 5, 5);}
  }

Later, I decided I needed to add/remove squares based on the page size. I got help here.

Welp, I had to change the animation function because it’s bind and won’t work on new divs. I researched and tried different functions, and this is where I’m at now:

$(document).ready(function(){
    $(document).on("webkitAnimationEnd mozAnimationEnd animationend", ".square", function(){
      $(this).removeClass("squareAnim");
    });
    $(document).on("hover", ".square", function(){
      $(this).addClass("squareAnim");
    });
});

But, it’s not working. I don’t know if $(document).ready is redundant (it was my attempt at delegation) but it still doesn’t work with or without it. Is there something I’m missing?

Edit jsfiddle

Answer

You have to rebind the events when you create the elements (i.e. onresize). It will not propagate to newly created elements if you just bind it once onready.

Also, onhover is deprecated (removed in jQuery 1.9) and should be replaced with onmouseenter and onmouseleave.

From jQuery’s docs:

Deprecated in jQuery 1.8, removed in 1.9: The name “hover” used as a shorthand for the string “mouseenter mouseleave”. It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the “hover” pseudo-event-name with the .hover() method, which accepts one or two functions.

$(window).on("resize", function() {
  multiplyNode(contain.querySelector('.square'), canAdd(), false);
  $(document).on("webkitAnimationEnd mozAnimationEnd animationend", ".square", function() {
    $(this).removeClass("squareAnim");
  });
  $(document).on("mouseenter", ".square", function() {
    $(this).addClass("squareAnim");
  });
}).resize();

Updated fiddle