0

I have been searching for a good answer to this for quite a while and can't seem to find a consensus on a simple way to do this. It also seems many previous ways have been deprecated.

Basically using the HubSpot platform I am creating a custom page. That page has a section that is dynamically added in. Since there is no callback function I can use and .load() or .ready() don't seem to work for dynamic content. How can I grab these DOM elements which take a couple seconds to load?

user3238454
  • 64
  • 1
  • 9

1 Answers1

1

.load and .ready wait for the DOM to load. This is going to be the raw html output by the server which means any content loaded dynamically will not exist and therefore can't be manipulated.

The easiest way is using JQuery .ajaxComplete() and attach it to the document.

Basically, it would become something like:

$(document).ajaxComplete(function() { /* Do Stuff */ });

The downside is that this will fire when ANY ajax call completes, not just the one you are after so if it's a slow-processing function, it's going to cause your page to lag pretty severely.

The best bet is to use this along with conditional statements to see if the data you wanted to manipulate has been loaded. E.g. if you want to modify an element with a class of "foo" once it's loaded, you could do something like:

$(document).ajaxComplete(function() { if($('.foo').length) { /* Element exists since length is greater than 0, do stuff */ });

It's still going to fire on every ajax call but at least this way it won't cause your page to lag too much since the conditional statement is going to fail until the document is loaded.

Also, depending on what you want to do to the elements, you might want to add some way of checking if it's been processed (e.g. by creating a boolean variable, check the value when you see if the element exists, and then change it once you have made your modifications).

ScarecrowAU
  • 194
  • 2
  • 9