javascript not running on newly added section

studio-umbrella
Shopify Partner
57 0 15

Hi community!

 

I'm creating a section that has JS inside the section file (inside <script></script>).

When I just add the section via the Theme Editor, no JS runs until I save. It doesn't even run if I edit the section with various fields. It has to be saved in order for the JS to be executed.

 

I'm using the "shopify:section:load" event listener too, but that is only in use after I save. 

Could this be a bug within Shopify???

 

This is quite problematic because if a customer wants to add a section to see how it will look, but doesn't want to save because it would affect the live site, he can't! 

 

Any help would be great!

Need Shopify design and development? Need a Shopify section? We'd love to hear from you!
Replies 6 (6)

studio-umbrella
Shopify Partner
57 0 15

Just bumping this up in case someone missed it. 🙂 

Need Shopify design and development? Need a Shopify section? We'd love to hear from you!

StoreTaskExperť
Shopify Partner
1 0 1

You can wrap the function with this.

 

 

{% if request.design_mode %}
  document.addEventListener("shopify:section:load", function(event) {
  });
{% endif %}

 

 


Reference:

https://shopify.dev/themes/architecture/sections/integrate-sections-with-the-theme-editor

ed_codes
Shopify Partner
13 0 6

I'm having the same problem. Did you ever find a solution? 

studio-umbrella
Shopify Partner
57 0 15

I did! 

You need to wrap the JS with the {% raw %}{% endraw %} tags.

So it would be <script>{% raw %} ...JS code... {% endraw %}</script>

 

That worked for me.

Need Shopify design and development? Need a Shopify section? We'd love to hear from you!
ed_codes
Shopify Partner
13 0 6

Thanks for the reply! Unfortunately, this doesn't work for me. I thought the raw tags were just for outputting liquid brackets. I can't even output a console log. 

studio-umbrella
Shopify Partner
57 0 15

oh, then maybe try using {% javascript %}...{% endjavascript %} tags.

I don't remember how I got it to work, but I believe the previous option is working for me as well...

Need Shopify design and development? Need a Shopify section? We'd love to hear from you!