Rollovers for Dynamically Created Buttons with JQuery

StuartProgramming Blog

The button rollovers using .hover with JQuery look great, but what about when the buttons will be created dynamically. In this instance, the buttons are in a column in a table. Additional table rows are created programmatically while using the form. How can you add a .hover event to your newly created buttons?

I've found a really simple answer to this problem.

When the DOM is loaded (check this with the document.ready function) this attaches a listener to every object of class ro-button. The listener responds to mouse movement over that element by executing a block of code which checks a variable in the data object (this will prevent us from attaching the listener twice) and then adding a hover event to the object. The hover event takes as parameters a function to execute when that object is hovered and un-hovered. In this case, we are applying the class ui-state-active and then removing it.

$(document).ready(function() {
   $('.ro-button').live("mousemove", function() {
      if (!$(this).data("init")) {
         $(this).data("init", true);

Hopefully others will find this useful as well.


StuartRollovers for Dynamically Created Buttons with JQuery