Search code examples
jquerymeteoriron-routersemantic-ui

Access HTML after this.render() in Iron Router


I need to apply some Semantic UI on newly rendered templates, but I have no idea how to get the rendered HTML from the router. Here's my code :

Router.route('/', {
  name: 'home',

  where: 'client',

  action: function () {

    this.render('home');
  },

  onAfterAction: function () {

    console.log( $('#homeSidebar') );

  }

});

Basically, $('#homeSidebar') should return the sidebar element, but it returns nothing as the HTML is not yet available. The only solution, so far, was to change the function like this

  onAfterAction: function () {
    setTimeout(function () {
      $('#homeSidebarToggle').on('click', function () {
        $('#homeSidebar').sidebar('toggle');
      });
    }, 200);    
  }

Which is neither clean nor safe. How can I run a function immediately as soon as the HTML is availble?


Solution

  • You should use onRendered callback on the template. Meteor uses template helpers, events and callbacks for manipulating DOM. Iron Router is just for routing)
    Your client/view.html:

    <template name="home">
      <div id="homeSidebar">
    
      </div>
    </template>
    

    Your client/view.js:

    Template.home.onRendered(function () {
      console.log($('#homeSidebar'));
    });