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?
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("");
});
});