I have some JavaScript code that I'd like to execute after a user clicks one of their folders -- it triggers the show action and show.js.erb, which renders the partial.
Show.js.erb, which is triggered when a user clicks on one of their folders, looks like this:
$("body").append( "<%=j render :partial => 'contents', :locals => {:folder => @folder } %>" );
It successfully injects the partial _contents.html.erb, which looks like this:
<script type="text/javascript">
d3JSON = function(){
d3.json("/folders/<%= @folder.id %>.json", function(error, data) {
if (error) return console.warn(error);
var folderChildren = [],
circle;
/*for (var i=0; i < data.submissions.length; i++) {
var submissionWords = data.submissions[i].content.split(' ').join('');
var size = submissionWords.length;
folderChildren[data.submissions[i].id] = size;
console.log(folderChildren);
};*/
var svg = d3.select("body").selectAll("svg");
circle = svg.selectAll("circle")
.data(data.submissions);
circle.enter().append("svg:a")
.attr("xlink:href", function(d){
return "http://localhost:3000/submissions/" + d.id;
})
.append("circle")
.attr("cy", function(d) {return d.content.length * 5 + "px";})
.attr("class", "floating")
.attr("cx", function(d){
return (d.content.length / 2) * 10 + "px";
})
.attr("r", function(d){ return (d.content.length / 2) * 1.2;});
circle.exit().remove();
});
};
d3JSON();
</script>
I've tested this JavaScript and it works, but when it's injected it is supposed to interact with the divs in the DOM and it doesn't. The divs are in my index.html.erb file, so they're already loaded when this JS is injected. I have tried lots of different things to try and get this working, but alas no luck Any advice? If I try to load something simple like alert()
through a partial it works, but I'm guessing this isn't working due to loading order of the DOM and js.
You're right about the loading order of the DOM and js. So what you can do is trigger a custom event in your show.js.erb
and listen to that event in one of your js
files and call the d3JSON();
there.
// show.js.erb
$("body").append( "<%=j render :partial => 'contents', :locals => {:folder => @folder } %>" ).trigger('show');
In one of your javascript files that is loaded in your page
$(document).ready(function(){
$('body').on('show', function() {
d3JSON();
});
});
And you don't need the d3JSON();
call in your _contents.html.erb
.
Give this a try.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With