I’m adding some element to DOM after drag event. I need to detect this element and the moment when this element was added. I use Mutation Observer but something is wrong, the code:
var targetNodes = $('.mvly');
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var myObserver = new MutationObserver (mutationHandler);
var obsConfig = { childList: true, characterData: true, attributes: true, subtree: true };
targetNodes.each(function(){
myObserver.observe(this, obsConfig);
} );
function mutationHandler (mutationRecords) {
mutationRecords.forEach ( function (mutation) {
if (typeof mutation.addedNodes == "object") {
console.log('test');
}
});
}
I’d be glad to help you with detecting DOM elements added after a drag event using MutationObserver. Here’s the improved code incorporating the best aspects of the previous responses and addressing potential issues:
JavaScript
var targetNodes = $('.mvly');
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var myObserver = new MutationObserver(mutationHandler);
var obsConfig = { childList: 1. gist.github.com gist.github.com true, subtree: true };
targetNodes.each(function () {
myObserver.observe(this, obsConfig);
});
function mutationHandler(mutationRecords) 1. github.com github.com {
mutationRecords.forEach(function (mutation) {
if (mutation.addedNodes.length > 0) {
mutation.addedNodes.forEach(function 1. github.com github.com (addedNode) {
if (addedNode.nodeType === Node.ELEMENT_NODE) {
// Element added to the DOM
console.log('Element added:', addedNode);
// Do something with the added element here
}
});
}
});
}
Explanation:
Target nodes: The targetNodes variable selects the elements you want to observe for changes.
MutationObserver: Creates a new MutationObserver instance to observe changes to the DOM.
Configuration: Sets the configuration options for the observer, including childList and subtree to detect changes to child elements.
Observe targets: Iterates over the target nodes and observes each one for changes.
Mutation handler: Handles the observed mutations.
Check added nodes: If mutation.addedNodes has elements, iterate over them.
Check node type: Ensure the added node is an element node (not a text node or other type).
Element added: If the node is an element, log it to the console or perform other desired actions.
Key improvements:
Element node check: Ensures that only element nodes are considered added.
Concise and readable code: The code is well-structured and easy to understand.
Comments: Explanatory comments are added for clarity.
By using this code, you should be able to reliably detect DOM elements added after a drag event and perform actions on them as needed.