JQuery "live" bug in IE 9

In working on a recent client project, I ran into the infamous "stop running this script" error in IE 9. Unfortunately this happened at the end of the project, and it was only occurring in IE 9 (go figure). After taking the JQuery apart what I found was that using JQuery's .live() feature to attach handlers to new HTML added to the DOM was causing the problem. This is a great feature for managing handlers ... when it works.

So that left me "live-less" and scrambling to find a new way to assign handlers to new DOM objects. This tutorial could easily be titled "how to implement JQuery live ... without JQuery live."

This might not be the best way to solve this problem, and I would love feedback on other approaches, but here is how I worked around this issue. The first thing I did is consolidated all my handlers into a function that could be called when new DOM elements were added.

function assignHandlerActions(){ }

Then I put all my assignments in this method:

function assignHandlerActions(){
  $(".addaday").click(function(event) {
    //new HTML is added to the dom with this selector is clicked
    //since there is new HTML we need to fire the assignment function
    assignHandlerActions()
    return false;
  });
}

The problem I found with this approach is that the the assignment function was being called multiple times, even when I just clicked on the "addaday" button once. At first I thought the event was bubbling up and causing a recursive loop, so I looked into event.stopPropagation() but this didn't seem to solve the problem. What I found is that selectors were being assigned a "click" handler over and over. I didn't know that if you assigned multiple click handlers to a selector (with the same function) it will fire that function multiple times. What I ended up doing was just unbinding the handler from all selectors before reassigning it:

function assignHandlerActions(){
  $(".addaday").unbind('click');
  $(".addaday").click(function(event) {
    //new HTML is added to the dom with this selector is clicked
    //since there is new HTML we need to fire the assignment function
    assignHandlerActions()
    return false;
  });
}

This keeps selectors from being given multiple assignments. After I was able to get this problem solved the script worked flawless in IE 9 ... without JQuery live.

Code JavaScript

Read This Next