2

I am so confused...I was working on my site and added some jQuery. Upon testing, I found that the jQuery didn't do anything. I then tried the most simple yet visible code I could think of:

<script type="text/javascript">
  $("html").click(function() {
    $("html").html("");
  });
</script>

but that didn't do anything either. So I tried that same code in the js console and got back this error:

Uncaught TypeError: $ is not a function
  at <anonymous>:2:1
  at Object.InjectedScript._evaluateOn (<anonymous>:848:140)
  at Object.InjectedScript._evaluateAndWrap (<anonymous>:891:34)
  at Object.InjectedScript.evaluate (<anonymous>:627:21)

and just entering $ just gives back "undefined".

I investigated and found that I had accidentally moved my Gemfile, and that maybe the server couldn't access the jquery-rails gem. But after I moved it back and restarted the server, the problem didn't go away.

Then I thought maybe I had some faulty code on my page that was preventing the jQuery from running. I removed all the code so it was a just a blank document, ran it, and tried again, but I got the same errors in the console.

The head of my app includes this:

<head>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
</head>

My app/assets/javascripts/application.js includes the line //= require jquery

And bundle install returns "jquery-rails 4.1.1".

I've ran plenty of jQuery before on the same page with no issues. It seems my server suddenly just stopped understanding jQuery. What on earth could be going on?

Jeff Caros
  • 919
  • 5
  • 12
  • 32

2 Answers2

14

Wrap it in a jQuery function, like this:

// Note the "$" inside function() - that's the key
jQuery( document ).ready(function( $ ) {

  $("html").click(function() {
     $("html").html("");
  });

});
Zack Katz
  • 1,310
  • 11
  • 9
  • Um...yeah, now it works. What on earth happened?? My other jQuery was working no problem like a day ago. – Jeff Caros Apr 10 '16 at 05:37
  • 1
    It's a race condition issue. You were calling `$` before it was loaded by page. In the above sample, the code within the function of the body is only executed once the page is finished loading. – Anthony E Apr 10 '16 at 06:11
  • That working for my stuff, but other wordpress's plugin doesn't work anymore... Even if i do it on a specific script js or after my html ... :/ I can't know why. If someone has any ideas ;) Cheers. – Kiloumap Mrz Aug 09 '18 at 14:01
0

Make sure you include jquery in app/assets/application.js:

//= require jquery
//= require jquery_ujs
Anthony E
  • 11,072
  • 2
  • 24
  • 44