开发者

Javascript: Is there a way to tell when a div has been added to an element?

Say I have a third party twitter widget on a page which keeps updating whenever there is a new tweet. Is there some way to figure out when a new div has been added to this widget? Is there an event or something I can hook onto (on maybe the widgets parent div)?

If there 开发者_Go百科isn't, how do I do this? Maybe hook onto the ajax calls the widget is making? How do I do that? It seems possible as firebug seems to be doing this but I can't tell how.


If you're using any kind of modern browser, you can use the DOM Mutation Events to listen for node changes. From the description of your question you're probably looking for DOMNodeInserted. If you must you can use a horrible setTimeout() hack, but in general it's better to wait for events than spin around waiting for something to happen.

Heck here is some example code because I am bored:

var widget = document.getElementById('mywidget');
widget.addEventListener('DOMNodeInserted', function (e) {
  if (e.target.nodeName !== 'DIV') return;
  // do some other code here
}, false);


Don't ktow if this is a good solution but you can periodicaly compare content of this div.


Giving the simplest answer first: I would suggest checking if the div exists after a second (time depending on many factors - I'm sure you understand the time specifics for your site). When adding a new element (such as your twitter widget) it's important to understand that each element (in your case, "a widget") comes with certain specifications which can have major differences compared to similar (on the surface similar) "widgets"

For a short answer: "It depends on the third party widget"

For the medium answer: "If you can look at how the widget is created, you can probably find a way to 'talk to it'"

For the longer answer: "It's actually not very difficult to create something to communicate with Twitter, so if that's what you want to learn I would suggest being more specific."

Hope SOMETHING OF THIS HELPS...

edit: Knowing nothing about the widget, I would probably set an interval to make requests from client to server, either by using javascript:setInterval() or setTimeout()... If I had time/resources, I would prefer a solution where you understand both Twitter and the widget though (saves time in the future if you want to think about what you've done)...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜