How to implement js code just for collection pages

Solved
Highlighted
Explorer
80 7 14

Well, the title should describe it. I wrote js code which should only be implemented on collection pages. 

If I put the code in a separate .js file in assets, in collection-template.liquid (I use minimal file) I also don't have a <head> or <body> tag.

Can anybody help me here?

Thank you!!!

0 Likes
Highlighted
Shopify Partner
41 5 13

This is an accepted solution.

I would keep it in the layout/theme.liquid file, right before the closing body tag if possible.

You can write a condition to check against the liquid template object to conditionally render the script tag.

 

{% if template.name == 'collection' %}
  <script></script>
{% endif %}

 

Check out the page on the template object for a full list of properties that you can check against.

0 Likes
Highlighted
Explorer
80 7 14

@kenput3r  

Thank you!! That was exactly what I was searching for!

Up to now I used to check for the length of an element, that is just placed on collection pages

 

if ($('#test').length > 0) {
  alert('exist');
} else {
  alert('sorry nope');
}

 

 It works, but I'm not too happy with that if code changes or who knows. Just not proper coding.

Thank you!!

1 Like