I have a page where some tweets are dynamically fetched from Twitter. It’s like a news ticker thing. The whole page is over here http://jsfiddle.net/R6D4R/.
The page works in jsfiddle because the content is already in there, whereas the content on the live site is dynamically placed into the divs. The ticker() function still works, but the if statement is not taking effect. Could anyone help me fix this?
EDIT:
Sorry guys, I didn’t clarify why the if statement is there for. The function works on its own, but I don’t want the function to run when there’s only one tweet. That’s why I have if (tickerli.length != 1). I should probably use > 1 instead of != 1, but you get the idea
OK, completely redoing my answer as I was confused about what you were asking:
To deal with dynamically added elements in your
ticker()function, you have to re-evaluate your selector on each call of the function like this:This was the previous answer when I thought you wanted help with event handling on dynamically added elements.
To install event handlers that will work on elements that are added dynamically in the future, you need to use delegated event handling. To do, you can use:
Note: there are two forms of
.on(), one is static and one is dymamic (uses delegated event handling). To use dynamic event handling, you bind the.on()handler to a parent element that is not dynamic and then you pass (as the 2nd argument to.on(), a selector that matches the dynamic element).In your jsFiddle for a click handler on the tweet text, that would work like this:
Note: jQuery
.on()was added in jQuery v1.7. For earlier versions of jQuery, use.delegate().