We ran into an issue this morning with Ninja Forms (NF’s): How do we run JS code to add Choices.js on field that appear via NF’s Conditional Logic?
NF’s suggest using Marionette and Backbone, but this appear to not work. Instead we used MutationObserver to listen to changes to the DOM.
Here is our code to listen and add JS choices to any new selects.
jQuery(document).ready(function ($) { let whatToObserve = {childList: true, attributes: false, subtree: true, attributeOldValue: false}; MutationObserver = window.MutationObserver || window.WebKitMutationObserver; let mutationObserver = new MutationObserver(function(mutationRecords) { let updateDom = false; $.each(mutationRecords, function(index, mutationRecord) { if (mutationRecord.type === 'childList') { if (mutationRecord.addedNodes.length > 0 && mutationRecord.target.localName === 'nf-field') { updateDom = true; } } }); if (updateDom) { // Custom logic here e.g. Choices new Choices('select.nf-element', { itemSelectText: '', shouldSort: false }); } }); mutationObserver.observe(document.body, whatToObserve); });
Comments are closed.