2

I am trying to make a bot that sends virtual currency over to another user. I have the bot search through a database for users. Before searching, the inner html of a division has no elements at all. After searching, it is then filled with several user links.

Because it takes a short while for results to appear, I need Javascript to wait for at least one anchor tag to exist. How can I do this?

Newbie
  • 115
  • 2
  • 2
  • 5
  • you can put your java script function below the html control then first control loaded then your java script function will execute – Nitin Kumar Oct 08 '16 at 06:59
  • Are you using asynchronous XMLHttpRequest? – alfadog67 Oct 08 '16 at 07:01
  • Please [edit] your question to include an example of the structure, and the script that populates the structure. –  Oct 08 '16 at 07:11
  • Note to close voters: this is NOT an exact duplicate of the linked Q&A. The linked Q&A requires jQuery; this does not. There is a significant difference between the two. – InteXX Apr 23 '17 at 17:36

5 Answers5

0

There are many, many better ways to do this, all of which stem from actually checking when the AJAX data populates the element itself, but the following will work:

var t = setInterval(function () {
  if ($("element").children().length > 0) {
    clearInterval(t);
    // do stuff
  }
}, 50);
Lucas
  • 16,930
  • 31
  • 110
  • 182
  • Create a new jQuery object, query the DOM, and call a function to return an array of children just to check the length of the array every 50 milliseconds then throw it all away if the length is 0 every time until your script finds it? That seems quite excessive. –  Oct 08 '16 at 07:03
  • 1
    Also, this question does not have a jQuery tag, [`Unless a tag for a framework or library is also included, a pure JavaScript answer is expected for questions with the javascript tag.`](http://stackoverflow.com/tags/javascript/info) –  Oct 08 '16 at 07:08
0

Using setTimeout() to delay the code a few seconds is risky, since on older browser/machines it may take longer than expected.

Use promise() instead, You can find documentation https://api.jquery.com/promise/ .

  • 1
    This question does not have a jQuery tag, [`Unless a tag for a framework or library is also included, a pure JavaScript answer is expected for questions with the javascript tag.`](http://stackoverflow.com/tags/javascript/info) –  Oct 08 '16 at 07:09
  • Okay, then use javascript promises. – Stan George Dec 08 '16 at 09:41
0

Using onload event, You can use onload with tag a. EX: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_img_onload

Kakada NEANG
  • 451
  • 1
  • 6
  • 16
0

I'm guessing this is an AJAX call.

You could use AJAX callback to check if you got any results from the server.

Something like this:

var tags_available = false;
$.ajax({
   ... the ajax stuff;
}).done(function(data){ // The callback
  if(data || $('#tags_element').lenght != 0){
    tags_available = true;
  }else{
    tags_available = false;
  }
})

Then:

if(tags_available){
  console.log("Tags available")
}
Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77
0

If I've understood you correctly you need to check if dom element have been updated/populated with new elements. There are a few ways you can achieve that:

1.) Using window.setTimeout function

function checkForChanges() {
  var observeThis = document.getElementById('observethis');
  if (observeThis.hasChildNodes()) {
    alert('yes');
    return;
    /*this is gonna execute only once */
  }
  window.setTimeout(function() {
    checkForChanges();
  }, 25);
}

checkForChanges();

/* this part is only relevant for demonstration. 
It shows what happens when dom element gets new child */
(function() {
  var observeThis = document.getElementById('observethis');
  var button = document.getElementById('button-append');
  button.addEventListener('click', function() {
    var anchorElement = document.createElement('a');
    anchorElement.href = "http://example.com";
    anchorElement.target = "_blank";
    anchorElement.innerHTML = "Link";
    observeThis.appendChild(anchorElement);
  }, false);
})();
<div id="observethis"></div>
<button id="button-append">append anchor</button>

2.) MutationObserver class

this is modern approach (I would also say recommended one).

function checkForChanges() {
  var observeThis = document.getElementById('observethis');
  // create an observer instance
  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      if (mutation.type === 'childList') {
        alert("insert your own code");
      }
    });
  });
  var config = {
    attributes: true,
    childList: true,
    characterData: true
  };
  observer.observe(observeThis, config);
  //observer.disconnect(); 
  //use observer.disconnect to end observations
}

checkForChanges();

/* this part is only relevant for demonstration. 
It shows what happens when dom element gets new child */
(function() {
  var observeThis = document.getElementById('observethis');
  var button = document.getElementById('button-append');
  button.addEventListener('click', function() {
    var anchorElement = document.createElement('a');
    anchorElement.href = "http://example.com";
    anchorElement.target = "_blank";
    anchorElement.innerHTML = "Link";
    observeThis.appendChild(anchorElement);
  }, false);
})();
<div id="observethis"></div>
<button id="button-append">Append Child</button>
Read more about MutationObserver here

3.) If you are just waiting to get a response from ajax callback and don't actually need to observe changes in dom then just use XMLHttpRequest. Or even better. Use new javascript fetch API (you are gonna need polyfill to ensure it works in most browsers)

AlFra
  • 379
  • 1
  • 6
  • 17