cadlac
cadlac

Reputation: 3158

Offloading jQuery to its own file

I'm confused on consolidating jQuery into it's own file. I'm able to do what I need with jQuery, but I either put each function in its own .js.erb file, or include it inline in the .html.erb file, wrapped with script tags. If I try to put them all in the same file, I can't get it to work.

I want to replaceWith() a different div whenever the user clicks on a link, specific to which link it is. Currently, I have each link pointing to a different action, each with it's own distinct .js.erb file - so I have about 12 files, each with only one link of jQuery - which works, but seems so messy.

An example link is like so:

<%= link_to({:action => 'economics'}, remote: true) do %><div id="department" class="economics">Economics</div><% end %>

And the assosiated jQuery (again this is the only line in the file economics.js.erb):

$('#target_div').replaceWith('<%= j render "economics" %>')

I feel like there has to be a cleaner way to do this.


I got it to work thanks to the comments below! Here is the general code

HTML - data-remote was the key!

<div id="render_form" data-target="target_div" data-remote="true"> economics </div>
<div id="render_form" data-target="target_div" data-remote="true"> other </div>
<hr />
<div id="target_div">Nil</div>

jQuery

$("div#render_form").click(function() {
    var targetId = $(this).data("target");
    var text = $(this).text();
    if (targetId.length > 0) {
        $(this).data("target");
        $('#' + targetId).text(text);
    }
});

jsFiddle can be found here!

Thanks for the comments!

Upvotes: 3

Views: 319

Answers (2)

Shadow Wizard
Shadow Wizard

Reputation: 66388

A shot in the dark as I'm not familiar with Ruby but from what I understand, you can add the target div ID to each source div:

<div id="department" class="economics" data-target="economics_target_div">

Then have this single block of jQuery code in your main file:

$(document).ready(function() {
    $("div[data-target]").click(function() {
        var targetId = $(this).data("target");
        if (targetId.length > 0) {
            //prevent replacing again:
            $(this).data("target", "");
            $('#' + targetId).replaceWith(this);
        }
    });
});

This will iterate through all DIVs having the above data attribute and handle their click event.

Live test case.

Upvotes: 3

abhir
abhir

Reputation: 1069

I'm not a jQuery expert, but in general, I like to separate all javascript for a single view into a single file rather than include them inline.

I believe this is the "Railsy" way to do it. A JS file for each view, ideally. Check out this blog on some more general info (http://xn--ncoder-9ua.dk/blog/2012/02/page-specific-javascript-in-rails-3/)

Now, when I do so, I also make sure to wrap the JS in $(document.ready(function()... to ensure that the script is run on pageload. Try that, and see if it works for you.

Upvotes: 0

Related Questions