userlkjsflkdsvm
userlkjsflkdsvm

Reputation: 973

JavaScript library loads twice in Rails

When I add the JavaScript library to the Rails asset folder and have it configured in my erb file using: <%= javascript_include_tag('scripts.js') %>, the HTML code with the classes associated with the JavaScript file load twice.

I have attached an example here. When I link the JavaScript files to the public folder this issue does not happen, but instead the JavaScript does not show up.

JavaScript

$(function() {
    $("a.page-scroll").bind("click", function(a) {
        var b = $(this);
        $("html, body").stop().animate({
            scrollTop: $(b.attr("href")).offset().top
        }, 1500, "easeInOutExpo"), a.preventDefault()
    })
})

Html.erb

<li>
    <a class="page-scroll" href="#portfolio">Portfolio</a>
</li>
<li>
    <a class="page-scroll" href="#me">About Me</a>
</li>
<li>
    <a class="page-scroll" href="#contact">Contact</a>
</li>

There are no relevant console errors.

Note: This works perfectly fine without Rails.

Upvotes: 0

Views: 1578

Answers (1)

Marrs
Marrs

Reputation: 716

If its a standard rails project out of the box, and the javascript/coffee file lives inside lib/assets/javascripts or vendor/assets/javascripts then it will automatically be pulled into rails asset pipeline via this line in the application.js file:

//= require_tree .

There is no need to use the javascript_include_tag inside the erb file if its pulled in by application.js (I am assuming that application.js is being rendered by some layout file via javascript_include_tag('application'), this is why its rendering twice).

If the js file lives in one of these directories, and you remove your javascript_include_tag from the erb file.... It should solve your double render problem.

Upvotes: 2

Related Questions