Shopify theme editor removes event listener's in section update

Shopify theme editor removes event listener's in section update

Velkamhell
Shopify Partner
16 2 0

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

```html
<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 %}
```

Replies 0 (0)