Using jQuery to target elements rendered in Meteor
jquery, meteor
Solution
You might be able to use the `Meteor.template.rendered` function for this purpose, since the problem seems to be that your DOM isn't rendered yet. Your template could look like this:
<template name="vis">
<div id="vis">
{{#each Actions}}
{{>visEntry}}
{{/each}}
</div>
</template>
<template name='visEntry'>
<div class="visEntry"></div>
</template>
And then you could use the Template.rendered callback like this:
Template.visEntry.rendered = function(){
var mydata = this.data,
el = this.find('div.visEntry');
// jquery code here;
}
You'll have access to the data associated with each template inside of `this`, and you can also use the built in `find` to fetch the appropriate dom element within that template. You can then set the CSS of whatever DOM element you'd like with the associated data. Furthermore, if the template is originally supplied a `Meteor.Collection` (instead of of a `fetched` source) then only the added/changed/moved templates will be rendered. In effect, I think this gives you what you were trying to do with `observe`.
Problem
I have been struggling with this for some time now and can't seem to find a solution that works. Hopefully someone here can help. I am trying to render a div for every entry in a collection, then use jQuery to target each div, take information stored in the entry corresponding with that div, and change its CSS according to the value of the data. Here is my template: ``` <template name="vis"> <div id="vis"> {{#each Actions}} <div class="visEntry" id="entry{{ID}}"></div> {{/each}} </div> </template> ``` I tried using cursor.observe() to give me a callback whenever and entry was added to the collection, but I can't use jQuery to select the newly rendered element. I can print any value from the selected entry through the console, use jQuery to select and modify a non-template div (hard coded in the HTML file) but when I select the element I want, it doesn't work. ``` Template.vis.Actions = function(){ var actions = Actions.find() actions.observe({ added: function(action){ var entryHeight = action.Duration var entryOffset = ($("#vis").height() - entryHeight) / 2 var target = "#entry" + action.ID; $(target).css({'background-color':'red'}) // Doesn't work $("#testDiv").css({'background-color':'red'}) // Works fine } }) return actions } ``` I have checked the source code of my live page, and the ID used in the jQuery selector is correct. I have four entries: entry1, entry2, entry3, and entry4, but they appear to be invisible to jQuery. This is driving me crazy, so if anyone knows what I'm doing wrong, I would love to hear some feedback.