0

I am having hard time trying to make $ work with my javascript. This is the line of code I am using. If i use jQuery, it works as expected but if I use $, it says $ is not defined. Any advices?

if (typeof Drupal !== 'undefined') {
  // Define Drupal behavior.
  (function ($, Drupal) {
    Drupal.behaviors.floatingButton = {
      attach: function(context) {
        $('body').css('background', 'red'); // $ is not defined
        jQuery('body').css('background', 'red'); // works fine
      },
    };
  })(jQuery, Drupal);
}
4
  • The answer for the other question answers your question too.
    – apaderno
    Aug 6, 2018 at 21:44
  • Thanks @kiamlaluno. But I already have jquery, drupal and drupalsettings as dependencies in libraries.yml.
    – cissharp
    Aug 6, 2018 at 23:00
  • It's code you are showing that is wrong: It should not be wrapped in a if statement.
    – apaderno
    Aug 7, 2018 at 3:52
  • It was different issues. Issue was inside attach I was calling function outside if (typeof Drupal !== 'undefined') and that was using $. Once I wrap that with (function($){......})(jQuery), it started working. Thank you.
    – cissharp
    Aug 7, 2018 at 13:09

0

Browse other questions tagged or ask your own question.