1

In Drupal 7 I used some JavaScript that required jQuery in the page.tpl.php file using the following code.

<script type="text/javascript">
    (function($) {
    $( ".mobile-menu-button" ).click(function() {
    $(".navigation").toggleClass( "visible" );
    $(this).toggleClass( "active" );
});
    })(jQuery);
</script>

Hod do I do this in Drupal 8? I have tried many ways of adding this code (with and without the jQuery argument above) in page.html.twig without success. I can see the code in the page source, but it fails to work.

1

You need to write JavaScript in a js file in your theme, declare a library within your theme and attach it globally or inside of a theme page attachments hook. You also need to depend on jquery from core in your library yaml definition as well.

See: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

  • Thank you for your answer. This is what I've been trying to do. How ever I haven't got it to work yet. – puudutus Apr 17 '17 at 16:09
  • @puudutus - than you should ask a more detailed question with information what you tried to do. Kevin's answer is absolutely correct and answers your question. Go through the docs and if you have any further problems you may ask in more details – Tobias Krause Apr 17 '17 at 17:01
  • Thank you for your comment. The answer is correct. The extra assurance helped me because I knew for certain what I needed to do without wondering if I'm trying to do the right thing.. working on my first Drupal 8 theme. – puudutus Apr 17 '17 at 17:21
  • You also have the JS in a closure, but brush up on that too. Most don't. This is one of the larger barriers of entry to people newer/newish to Drupal, particularly 8. – Kevin Apr 17 '17 at 17:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.