Reputation: 979
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?
Upvotes: 2
Views: 28875
Reputation: 11
In my case, I was trying to use an HTML element with my code block for a specific page in WordPress. However, this caused a "$ is undefined" error because jQuery wasn't fully loaded yet. To resolve this, I moved the code block to the header section, where it works just fine.
Upvotes: 0
Reputation: 1320
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("");
});
});
Upvotes: 15
Reputation: 11235
Make sure you include jquery in app/assets/application.js
:
//= require jquery
//= require jquery_ujs
Upvotes: 0