Trying to add a bit of jQuery/javascript to a template

I added this script to the /frontend/components/primaryNavMenu.tpl

<script>
$(document).ready(function(){
  $('.dropdown-submenu a.test').on("click", function(e){
    $(this).next('ul').toggle();
    e.stopPropagation();
    e.preventDefault();
  });
});
</script>

When I do this, the entire header menu fails to load as well other parts of the page. No console errors

{literal} <script>...</script> {/literal}

1 Like

Thanks @Vitaliy . That helped.

However, I have another issue. When I pasted in the above code, I get an error “$ is not defined” on the very first line: $(document).ready(…)

Seems to suggest jquery has not been loaded at this time, but I do see jquery.min.js (v1.11.0) loaded according to my developer tools.

If I add my own jquery library right before this, then it works

<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
  $('.dropdown-submenu a.test').on("click", function(e){
    $(this).next('ul').toggle();
    e.stopPropagation();
    e.preventDefault();
  });
});
</script>

But obviously I don’t want to do that. So just wondering why this is. Is jquery mapped to a different symbol other than $? Is it using a different jquery library that I’m not aware of?

Our site is at Open Journal Systems

It looks like jquery is being loaded as at the end of the body tag.

If I’m reading that correctly, the library will not be available until the page is rendered. This may speed page rendering slightly, but I think it will prevent the functional insertion of $(document).ready() earlier in the DOM.

@NateWr might have some pointers here.

1 Like

@ctgraham is right. Move your <script> tag to after the {load_script} tag in the footer.tpl template.

@NateWr that worked. thanks

1 Like