J Seabolt
J Seabolt

Reputation: 2998

Rails app JavaScript not working when placed in application.js

I have a Rails app. The JavaScript works perfectly when it is included in the index.html.erb view in a script tag. The JavaScript doesn't work at all when I place it in my application.js file.

Here is my entire application.js file. This code does not work:

//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require turbolinks
//= require_tree .


var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
            panel.style.display = "none";
        } else {
            panel.style.display = "block";
        }
    }
}

This exact same code works perfectly when included in a script tag in the actual view:

<script>
var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
            panel.style.display = "none";
        } else {
            panel.style.display = "block";
        }
    }
}

</script>

Can someone help me figure out why this is happening? Thanks

Upvotes: 1

Views: 775

Answers (1)

max
max

Reputation: 102443

Your code is not being run because its not being included in the compiled application.js. You can verify this by looking at the source of the javascript file in the browser.

You need to add require_self to the sprockets manifest which injects the contents of the file itself:

//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require turbolinks
//= require_self
//= require_tree .

You only need to do this for your main "manifest" file as files required by require_tree . are of course included.

See:
- The Assets Pipeline - 2.4 Manifest Files and Directives

Upvotes: 1

Related Questions