Can't find HTML elements after render


#1

I’m using a jQuery plugin, mainly to add tooltips to certain elements in my templates, but they only work on the first, initial, render of the page. If I try to use a tooltip inside a currentUser condition, or any other template include like {{> myTemplate}} it can’t find the elements in those templates.

I’m including my file in /startups/client/index.js
import '/public/js/tooltip.js';

For example, the code below can’t locate “after-rendered” elements

var targets = $( '[rel~=tooltip]' ),
    target  = false,
    tooltip = false,
    title   = false;

targets.bind( 'mouseenter', function() { console.log('Found element'); }

I have tried importing the file in the js files for each template, too, without any success.

Of course this could be related to jQuery itself, but it’d be nice to come to some conclusion eitherway.


#2

Most likely the issue is that the elements are not added to the DOM yet when this code runs. You’ll probably want to move this code into a template’s onRendered callback

Template.myTemplate.onRendered(function(){
    this.$('[rel~=tooltip]').tooltip();
});

#3

The problem is that I will have to do this for every single template and that’s not very effective


#4

Maybe try putting it in a top level template?


#5

Or install aldeed:template-extension and put it in a global Template.onRendered hook. then it will run for every template