hawmack13
hawmack13

Reputation: 233

Rails 4 Jquery loads but doesn't work

I'm trying to get some simple jquery working with a Rails2 app migrated up to Rails4. The js worked fine in Rails2 but not in Rails4.

I understand Turbolinks interferes with Jquery document ready, so I've removed it from the manifest file in assets and the gem in my gemfile. I re-ran Bundle Install and restarted my app.

I have confirmed that Jquery loads and I can see all the javascript loading in my firebug window. Regular javascript will run just fine; however anything starting with a $ is just fails silently.

Example:

<script>

$(document).ready(function(){
alert("I'm alive");
});

</script>

Even this won't work...but a simple alert works just fine. I'm scratching my head here.

Yes...this is right on the page. The js I need is über simple....usually just a one liner inside document ready.

I've googled this extensively and looked through Stack exchange. Any help is appreciated.

Upvotes: 1

Views: 654

Answers (2)

billrichards
billrichards

Reputation: 2060

It might be conflicts with prototype.js? You could also get the jquery-rails gem and do

rails g jquery:install 

At least for me, I don't want to think about whether I remembered to include jquery everywhere it's needed. Plus I believe jquery-rails takes care of any potential prototype.js conflicts.

EDIT My problem was Turbolinks, so just in case someone else arrives at this page like I did, you need to do

$(document).on('page:load ready', function()

instead of

$( document ).ready(function()

https://stackoverflow.com/a/22838992/1094092

"Turbolinks makes following links in your web application faster. Instead of letting the browser recompile the JavaScript and CSS between each page change, it keeps the current page instance alive and replaces only the body and the title in the head. Think CGI vs persistent process." https://github.com/rails/turbolinks

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115202

Make sure you have included jQuery library ; In order to work jQuery you need to include jQuery library. Also the script should be after the jQuery library.

<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script>    
 $(document).ready(function(){
    alert("I'm alive");
 });    
</script>

Upvotes: 1

Related Questions