Section doesn't run javascript after edit

Solved
Miki5
Tourist
3 1 0

Hi,

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

 

0 Likes
Miki5
Tourist
3 1 0

This is an accepted solution.

Figured it out. I now have a event listener for shopify:section:load. This fixes my problem.


0 Likes
HarryGehlot
New Member
3 0 0
i tried this in product page but notworking
document.addEventListener('shopify:section:load', function(event) {
  console.log(event)
});

Can you give me some example for this.

@Miki5 wrote:

Figured it out. I now have a event listener for shopify:section:load. This fixes my problem.



0 Likes
Miki5
Tourist
3 1 0

Hi Harry,

sorry for the late reply

I have following code in a .liquid file which is inside the sections folder (it should actually also work in any other folder as long as it is loaded into the html):

 

<script>
document.addEventListener("shopify:section:load", function(event) {
    if(event.detail.sectionId === '{{section.id}}') {
        loadFeed();
    }
});
</script>

 

 Hope that helps.

Also check out my question and the answer I got on StackOverflow: https://stackoverflow.com/questions/61207535/shopify-section-doesnt-run-javascript-after-edit

0 Likes