In this article, we'll look at utilizing the Mutation observer and jQuery to Influence SuiteCommerce SMT Content.
Need a refresher on working with SuiteCommerce SMT (Site Management Tools)? Check out out tutorial on working with Site Management Tools (SuiteCommerce CMS).
Affecting SMT Content
SMT content blocks, such as image sliders, are loaded onto the page after the code in extensions runs. You are NOT able to use the following to affect content within SMT.
layout.on('afterShowContent', function () {}
OR
$( document ).ready(function(){}
It is possible to affect SMT content by adding an HTML block to SMT and then adding your jQuery in there.
However, a best practice is to use the Mutation Observer and jQuery
Using the Mutation Observer
Here is a boilerplate Mutation Observer that is getting a specific class within an SMT content block.
const observer = new MutationObserver(function(mutations){
// set a boolean flag to check if the element I'm looking for is here
let contentFound = false;
// Iterate over all mutations that have occurred
mutations.forEach(function(mutation){
// Skip this mutation if no nodes were added to the DOM
if (!mutation.addedNodes) return;
// Loop through all nodes that were added in this mutation
for (let i = 0; i < mutation.addedNodes.length; i++) {
// Wrap the added node in jQuery so we can use jQuery on it
let $node = jQuery(mutation.addedNodes[i]);
// Check if the added node is the class I need
if($node.hasClass('class-to-edit')){
// If so, set flag to true
contentFound = true;
}
}
});
if (contentFound){
jQuery('.class-to-edit').each(function() {
// jQuery goes here
});
}
});
// !Required for the Observer
// Configuration of the observer:
const config = { childList: true, subtree: true };
// Select the node that will be observed for mutations
const targetNode = jQuery('body')[0]; // You might need to target a more specific part of your page
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
Do not forget the config, targetNode, and observer.observe below.
Get stuck in a step during this article?
We like to update our blogs and articles to make sure they help resolve any troubleshooting difficulties you are having. Sometimes there is a related feature to enable or field to fill out that we miss during the instructions. If this article didn't resolve the issue, please use the chat and let us know so that we can update this article!