jQuery error in a theme I'm trying to run a jquery script for my Drupal 8 site, but in the error console, I get a TypeError: $ is not a function. I know this usually happens when jQuery isn't loaded, but the jquery.min.js is loaded fine. Is it loaded too late? Do I perhaps need a wrapper?

In my theme.libraries.yml, I have the following:

global-styling:
  version: 1.x
  css:
    theme:
      css/style.css: {}
  js:
    js/script.js: {}
  dependencies:
    - core/jquery


My script is simply

$('#some-element').on('click', function() {
  // Do something
}


I would think this is all I need, or am I overlooking something?

Edit:

I don't think this is a duplicate question since:


This is Drupal 8
The dependency is defined in the libraries file. I would think this would take care of exactly the problem described in the other question.
In Drupal 8 jQuery is added in the non intrusive way, this means that $ is not defined in the global space.

What you should do is to use closures (this is a very good idea, as it makes it easy for you to fix potential issues with colliding variables names. $ is used by other frameworks as well.

This is done by wrapping your code in a anonymous function so you don't need to get variables from the window object but can get them from the function definition. This means that you can easily change the source one place and it will effect all of the script you have written.

(function ($, Drupal) {

  // It's best practice to use strict mode, can help avoid some browser issues.
  'use strict';

  // Generally you always want to use behaviors, remember to depend on Drupal js.
  Drupal.behaviors.name = {
    // Called on document ready and when no elements is added to the page.
    attach: function (context, settings) {
      $(".selector", context)...
    }
  }

  // Sometimes you just want to do something when DOM is ready.
  $(document).ready(function() {
    // Stuff to do as soon as the DOM is ready;
  });

})(window.jQuery, window.Drupal);