Creating index.js in assets and adding it to theme.liquid

Hello,

I am a beginner and I have recently learned that it’s better to put all your javascript code in one file in the assets folder and then import it to the theme.liquid file. I know I can import the js file like this:


Now let’s say in my collection.liquid, I have this js code,

{% form 'product', product %}
        
            
            

Variants

            

            
                
                 
                    
            

        

        

        
            

                 
          
                
            

            
                 
            

        
     
    {% endform %}

I was wondering how to move the js code from the collection.liquid to my index.js file. And then import the code somehow on my collection.liquid

Hi @avocado23 ,

You simply add the code in the index.js without the tag. One thing you have to note is this code will apply to any of the elements with id of product_variants. Your code might also return null.

document.querySelector('#product_variants').addEventListener('change', function(e) {
                        var selected_variant= e.target.value;
                        document.querySelector('#add-cart').value= selected_variant;
                    })