I created a simple custom section with one button, and one schema setting (a checkbox). I also created a script where I added an event listener to the button. The problem is that the first time the custom section is loaded the button listener works properly, but once I change any settings of the section, in this case, the checkbox, the button event listener stops working and the event doesn't fire anymore. In the docs I found that with every change in the section setting the HTML will be re-rendered, added, or removed, that means that every time the section is updated I have to add all the event listeners again, and 'restart' all the DOOM related logic that I had done in javascript? Thanks a lot, here is the code in case it helps <div class="section-wrapper"> <button id="button1" type="button"> Click me </button> </div> <script> const button1 = document.querySelector("#button1"); button1.addEventListener('click', () => { console.log('Hello world'); }); </script> {% schema %} { "name": "Custom Section", "tag": "section", "limit": 1, "settings": [ { "type": "checkbox", "id": "checkbox", "label": "Checkbox", } ], "blocks": [], "presets": [ { "name": "Custom Section", "blocks": [] } ] } {% endschema %}
Jese Leos
August 19, 2024
Verified user
The problem could be resolved by ensuring that the necessary JavaScript is re-executed when a specific section of the page is reloaded. document.addEventListener('shopify:section:load', function () { handleButtonClick("===>> Hello world reloaded!!! <<=== "); }); Complete Code Snippet: <div class="section-wrapper"> <button id="button1" type="button"> Click me </button> </div> <script> function handleButtonClick(optionalValue = '') { const button1 = document.querySelector("#button1"); button1.addEventListener('click', () => { console.log(`${optionalValue ? optionalValue : ' ===> Hello world! <=== '}`); }); } document.addEventListener("DOMContentLoaded", function () { handleButtonClick(); }); /* Re-execute any JavaScript needed for the section to work and display properly, as if the page had just been loaded. */ document.addEventListener('shopify:section:load', function () { handleButtonClick("===>> Hello world reloaded!!! <<=== "); }); </script> {% schema %} { "name": "Test Section", "tag": "section", "limit": 1, "settings": [ { "type": "checkbox", "id": "checkbox", "label": "Checkbox" } ], "blocks": [], "presets": [ { "name": "Test Section", "blocks": [] } ] } {% endschema %}