Can't find HTML elements after render

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.

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();
});

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

Maybe try putting it in a top level template?

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

1 Like