Unloading jQuery into its own file
I am confused about consolidating jQuery into my own file. I can do what I need with jQuery, but I either put each function in my own .js.erb file or include it in an .html.erb file wrapped in script tags. If I try to put them all in one file, I cannot get it to work.
I want to replaceWith()
differentiate div
whenever a user clicks on a link defined for which link it is. I currently have each link pointing to a different activity, each with its own .js.erb file - so I have about 12 files, each containing just one jQuery link - which works but seems so confusing ...
An example link is like this:
<%= link_to({:action => 'economics'}, remote: true) do %><div id="department" class="economics">Economics</div><% end %>
And the associated jQuery (again, this is the only line in the economy.js.erb file):
$('#target_div').replaceWith('<%= j render "economics" %>')
I feel like there must 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);
}
});
Thanks for the comments!
source to share
Snapshot in the dark, as I'm not familiar with Ruby, but from what I understand, you can add the target div id to each div source:
<div id="department" class="economics" data-target="economics_target_div">
Then this single jQuery code block 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 over all DIVs that have the above data attribute and handle their click event.
source to share
I'm not a jQuery expert, but in general I like to strip all javascript for one view in one file rather than include them in a line.
I believe this is the "Railsy" way of doing it. Ideally, a JS file for each view. Check out this blog for more general information ( http://xn--ncoder-9ua.dk/blog/2012/02/page-specific-javascript-in-rails-3/ )
Now that I do, I will also make sure to terminate the JS in $(document.ready(function()...
to ensure that the script is run on the pageload. Try this and see if it works for you.
source to share