Reputation: 10878
Much like the experimental web components: custom html elements I want to replicate the behaviour but by using divs and certain classes and performing an action on them. Like so I want to do something with a element with a specific class as soon as it created.
For example:
<div class="api-list" data-api-link="api/users/1/posts" data-api-template="post-item.html">
// List items
</div>
So with this, javascript should detect that hey a 'api-list' element was created. Is there such thing as adding an event handler on the body to fire an event if 'api-list' has been added to the dom?
Why not just attach it to the element directly, you ask? My site is single page and I use ajax to inject the content, therefore it needs to dynamically load things.
Upvotes: 0
Views: 79
Reputation: 4904
Mutation Observer can be used to solve your issue. Browser support for Mutation Observer
You can check this plunker, I just created using your sample api-list
.
We observe any change in the childList
for the conatiner
, if there are changes then loop over those changes and check if the conditions are met.
var divApiList = document.createElement('div');
divApiList.classList.add('api-list');
divApiList.textContent = '////////THE LIST////////';
var container = document.getElementById('container');
var counter = 1;
function addApiList (){
var apiList = divApiList.cloneNode(true);
apiList.textContent += counter;
container.appendChild(apiList);
counter++;
}
function addNonApiList() {
var div = document.createElement('div');
div.textContent = 'This is not api-list div';
container.appendChild(div);
}
// This can be in different file
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
Array.prototype.forEach.call(mutation.addedNodes, function(node){
if(node.classList.contains('api-list')) {
alert('Api-List added');
}
});
});
});
// configuration of the observer:
var config = { childList: true, subtree: true };
// pass in the target node, as well as the observer options
observer.observe(container, config);
// later, you can stop observing
// observer.disconnect();
#container {
border: 1px solid red;
}
<h1>Mutation are checked for the container below</h1>
<div id="container">
<div>This is not api-list div</div>
<div>This is not api-list div</div>
</div>
<button onclick="addApiList()">Add api-list</button>
<button onclick="addNonApiList()">Add NON api-list</button>
Please Note: I have never used Mutation Observer in production, so I am not sure if there are any issues using it. Please correct the answer if there can be any improvements
Upvotes: 1