Need help: Debugging JavaScript for the Canvas App (it works in desktop and mobile browsers)
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-05-2024
04:51 PM
So now that I understand how Mutation Observers work, I'm happily coding away and doing all kinds of cool non-API things in Canvas. Life is good.
Almost.
See, there is one piece of code that is working beautifully in Canvas in the browser, both desktop and mobile, and on my phone when I go to Canvas via a browser. However, it doesn't work in the Canvas App on mobile. I can't debug using Chrome because the issue is being only caused within the app.
Mind taking a peep at this code and letting me know why the App wouldn't like it but browsers do? In the comments I put other code that works in the App for the first of three cards only; I need to expand it to include more cards. This code below doesn't work for any cards in the App.
function initializeCards(cards) {
cards.forEach(card => {
if (!card.classList.contains('is-flipped')) { // Optional: Avoid duplicate listeners
card.addEventListener("click", function () {
card.classList.toggle('is-flipped');
});
}
});
}
// Create a MutationObserver instance
const observer = new MutationObserver((mutations) => {
let newCardsFound = false;
mutations.forEach(mutation => {
// Check for added nodes in each mutation record
mutation.addedNodes.forEach(node => {
if (node.nodeType === Node.ELEMENT_NODE && node.matches(".card__inner")) {
newCardsFound = true;
initializeCards([node]); // Initialize the newly added card
}
// If the added node contains child nodes, check those as well
if (node.nodeType === Node.ELEMENT_NODE) {
const cards = node.querySelectorAll(".card__inner");
if (cards.length > 0) {
newCardsFound = true;
initializeCards(cards); // Initialize all newly added cards
}
}
});
});
// If new cards were found, you could choose to keep observing or disconnect
if (newCardsFound) {
// Optionally, you might want to keep observing for more changes or disconnect here
// observer.disconnect(); // Uncomment if you want to stop observing after initialization
}
});
// Start observing the document body for changes
observer.observe(document.body, { childList: true, subtree: true });