Search code examples
javascriptshopifyliquidshopify-template

Shopify Section doesn't run javascript after edit


I wrote a custom Shopify Section. It contains javascript code that needs to be executed on page load because it does some DOM manipulations.

I noticed that if I change the sections settings in the Shopify Editor, the javascript is not executed again (The Shopify Editor replaces the sections DOM node with a node with updated values). This means the JS generated DOM nodes are lost.

Following code should demonstrate this behaviour. You see during the initial load a hi in the console. However if you change the value of title_text in the editor, you see the updated text in the page but in the console you see no new hi logged from JS. In my opinion there should be a second hi.

Does anyone know what I am doing wrong?

{{ section.settings.title_text }}
<script>
  console.log("hi");
</script>

{% schema %}
{
  "name": {
    "de": "Test",
    "en": "Test"
  },
  "settings": [
    {
      "type": "text",
      "id": "title_text"
      "label": "Text",
      "default": "Text"
    }
  ],
  "presets": [
  {
    "name": {
      "de": "Test",
      "en": "Test"
    },
    "category": {
      "de": "Test",
      "en": "Test"
    }
  }
]
}
{% endschema %}


Solution

  • You are not doing nothing wrong, Shopify refreshes the DOM, but not the Javascript when you edit it from the customize panel.

    In order to reinit your javascript logic you need to hook to the event shopify:section:load. This event fires on each modification.

    So for example you need to do the following:

    document.addEventListener("shopify:section:load", function(event) {
      console.log(1)
    });
    

    And add any JS that you like to reinitialize in the callback function.

    More on the provided events can be seen here: https://shopify.dev/tutorials/develop-theme-sections-integration-with-theme-editor