andersr andersr - 7 months ago 209
Javascript Question

Meteor with Semantic UI dropdown behavior not working

I am currently trying to integrate Semantic UI into my app. The visual styling is displaying fine. However, behaviors do not appear to be working and I am not able to raise any form of exceptions in my console to help with debugging.



Some relevant code snippets:

Markup for a user nav dropdown:


<div class="ui dropdown link item">
{{currentUser.name}}
<i class="dropdown icon"></i>
<div class="menu">
<a class="item">Sign Out</a>
</div>
</div>


custom.semantic.json file:

{
"definitions": {
...
"dropdown": true,
...
}


}

Invoking the dropdown in /client/client.js (though not sure if this is needed):

$('.dropdown').dropdown({
transition: 'drop'
});

Answer

jQuery plugins need to be initalized when the corresponding HTML elements have been inserted in the DOM, which is usually the case in standard server side rendered webapps, but Meteor takes a different approach by using client side reactive templating, all the HTML generation is done in the browser.

This is why you need to initialize jQuery plugins when Meteor has done inserting your dropdown in the document, you can use the template onRendered lifecycle event to detect when you can safely activate the widget behavior.

JS

Template.dropdown.onRendered(function(){
  this.$(".dropdown").dropdown();
});

HTML

<template name="dropdown">
  <div class="ui dropdown link item">
    {{currentUser.name}} <i class="dropdown icon"></i>
    <div class="menu">
      <a class="item">Sign Out</a>
    </div>
  </div>
</template>