0

A few things I've read have led me to the ready() function, but that seems to run as soon as the document itself is ready, regardless of what element you actually call it on. For example, I'm used to running things when the page is loaded like this:

$(document).ready(function() {
  window.alert("foo");
});

What I'm trying to do is run a script when an element with a certain is loaded. That element is added to the page dynamically, and not when the page is initially loaded. I've tried this:

$("#element-id").ready(function() {
  window.alert("foo");
});

But that runs on page load, regardless of what id I pass in. Whether or not an element with the passed in id exists on the page or not, or is loaded dynamically, the function always runs on page load, and never again.

How do I tell jquery to run a function when an element is loaded? I'm using jQuery 2.1.4.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
ewok
  • 20,148
  • 51
  • 149
  • 254
  • Since you load the element dynamically, can't you just call your function after that? – tymeJV Jul 03 '18 at 20:04
  • How are you adding the element, please show enough [mcve] code that we can reproduce your problem. – David Thomas Jul 03 '18 at 20:04
  • I'm not actually loading the element myself. I'm writing a plugin for bitbucket, and trying to run some javascript when the edit pull request dialog is loaded. – ewok Jul 03 '18 at 20:05
  • Maybe somethign like this: https://stackoverflow.com/questions/1960919/jquery-watch-for-domelement-changes ? – lealceldeiro Jul 03 '18 at 20:06
  • 1
    You would have to watch the dom then like [this question](https://stackoverflow.com/questions/2844565/is-there-a-javascript-jquery-dom-change-listener) and check if the changes reflect your element being added – Patrick Evans Jul 03 '18 at 20:06
  • 2
    There is nothing built into jQuery core that does what you want....'\ – epascarello Jul 03 '18 at 20:09
  • 1
    The `.ready()` event ignores the element, it's always for the document. – Barmar Jul 03 '18 at 20:26
  • Usually DOMs in static html file are loaded synchronously, while images inside DOMs are loaded asynchronously, you may notice when you try to open a web page on slow internet, the text will loaded first then slowly the images are loaded. So you might need certain images loaded inside the element. – Liang Jul 03 '18 at 20:28

0 Answers0