V
V
VitStar2015-09-29 14:58:20
JavaScript
VitStar, 2015-09-29 14:58:20

ReferenceError: $ is not defined error in WordPress?

Good afternoon! I made up the menu template and it works fine.
I started to pull this layout on wp, there was a problem, the menu does not work.
In the console writes ReferenceError: $ is not defined
The code of this file

$(document).ready(function(){ 
  var touch 	= $('#touch-menu');
  var menu 	= $('.menu');

  $(touch).on('click', function(e) {
    e.preventDefault();
    menu.slideToggle();
  });
  
  $(window).resize(function(){
    var w = $(window).width();
    if(w > 767 && menu.is(':hidden')) {
      menu.removeAttr('style');
    }
  });
});

And he everywhere swears at an anonymous function.
What could be the problem ?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Denis Ineshin, 2015-09-29
@VitStar

Before the place where you have this script included, include jQuery. For example like this:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

S
Sergiu Mitu, 2015-09-29
@EaGames

wrap your code in:

(function($) {
//тут ваш код
})(jQuery);

and everything will work

D
Dmitry Korolev, 2015-09-30
@Apathetic

I think it's important to mention that jQuery in WP by default runs in noConflict mode, which disables the use of the $ character as a shortcut to the jQuery() function.
The answer that you marked as correct is not, unlike Sergey 's answer . Indeed, the best way out is encapsulation. Although there are other ways. For example, you can write one line at the beginning of your script:
var $ = jQuery;

I
Ivanq, 2015-09-29
@Ivanq

The error is banal. Even a few.
Check if jQuery is included.
The second line from the bottom is an extra semicolon
. I don't know much about jQuery, but maybe I should put "touch" in quotes?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question