JS not working [Kirby Newbie]

Hi,

I have tried using the search function but unable to find an answer.

I am trying to add an “active” class when my menu icon is clicked.

// Toggle Navigation when Burger Button Clicked

$(document).ready(function(){
$(’.menu-icon’).click(function(){
$(’.menu-icon’).toggleClass(‘active’);
$(“nav”).toggleClass(‘active’);
$(“body”).toggleClass(‘active’);
});
});

I have added this to: assets/js/nav.js and then added <?= js('assets/js/nav.js') ?> to the header and tried in the footer php files. I have set up all the relevant HTML and CSS and yet it doesnt seem to work.

This is my first time using Kirby and im fairly new to php and js and I am wondering if im missing something?

Thank you

Since you are using jQuery syntax, have you loaded jquery prior to loading your custom JS?

If you only need JS to toggle the navigation, you’d better go with vanilla JS instead of loading a big bad library just for a few lines of code, though…

Yes, I read that as I got this error in the console: Uncaught ReferenceError: $ is not defined, but I am unsure how to load the jQuery beforehand.

I will also have a look at Vanilla JS, thank you for the recommendation!

  <?= js('assets/js/jquery.min.js'); ?>

Adapt path and filename as needed (if you really want to do that).

Basically like your loaded the other JS file, but of course, you would have to download jQuery first, unless you want to load it from CDN. But jQuery is dead, even Bootstrap doesn’t use it anymore :wink:

Awesome! I understand now!

I have just added this:

<script
  src="https://code.jquery.com/jquery-3.6.0.min.js"
  integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
  crossorigin="anonymous"></script>

Into: /assets/js/jquery.min.js and then added <?= js('assets/js/jquery.min.js') ?> to the header and it still didnt work, yet it works when I add the script tags into the header - hmm…

Thank you very much for the info. I will use this as a quick workaround for now to get the style, and then look into Vanilla JS for sure.

Yes, you cannot use script tags in a JS file, that doesn’t make sense, that code would indeed go into the header.

1 Like

Thanks for your help!