JQuery is not firing when loading html from assets

Solved
Highlighted
New Member
3 0 0

I have a set of large custom dropdowns that I am loading to the cart via cart-template.liquid. The html file is located in the assets folder, due to the code being too large for the cart-template.liquid file. When part of the html code is loaded into the cart-template.liquid file (say, 6 of the 50 dropdowns), the jQuery fires correctly. When it loads from the html file inside the assets, the code doesn't fire. I have tested moving the jQuery function, but it doesn't seem to work.  

<div id="PrisonDropdown">
</div>   
<script>
jQuery(function(){
$("#PrisonDropdown").load('https://cdn.shopify.com/s/files/1/0060/7577/7135/t/2/assets/PrisonDropdown.html?v=10490266648353359843');
});
</script>

I am loading the jQuery using the theme.liquid file, as the last lines before the end of the the head tag.

{% if template == 'cart' %}
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js" type="text/javascript"></script>
     <script type="text/javascript">
          jQuery(function() {
            $('.states').on('change', function(){
            var selected = $(this).val();
            $('.select-list').addClass('select-hidden');
            $('[id="' + selected + '"]').removeClass('select-hidden');

            })
          });

     </script>
{% endif %}

 

0 Likes
Highlighted
Shopify Partner
3 1 0

This is an accepted solution.

This is likely because the elements that you are targeting with jQuery are not actually loaded into the DOM yet.  In other words, the dropdown with class 'states' does not exist yet because you are adding this code to the top of the html (before the closing head tag).  If you move the snippet for the dropdown change to above the closing body tag then it will likely work.  Keep the jquery include in head however.

0 Likes
Highlighted
Shopify Partner
399 30 51

@doverman 

Can you share your store URL?
There are few reasons for that because you are adding both scripts on DOM ready and it is not able to get resources at the same time.

Akshay Vaghasiya

Shopify Expert | Skype: akshayvaghasiya84
 - Like and Mark as an Accepted Solution if my reply helpful
 - Feel free to contact me on akshayvaghasiya84@gmail.com or akshayvaghasiya@lavitastic.com for any queries
 - Want to modify or custom changes on store hire me .
0 Likes
New Member
3 0 0

Thanks for the help @philipvas , I ended up using your solution and using window load rather than DOM load and it is working perfectly now. 

0 Likes