Search code examples
javascriptjquerymeteormaterialize

Two clicks needed to load Modal and SideNav (Meteor with Materialize)


I have a strange problem with my Materialize navigation in Meteor. The weird thing is that when I click a link in the navigation, the sidebar or modal is only loaded on the SECOND click. Thus, I have to click the link once (where nothing happens) and then again for the element to appear. After that, the element loads on any click (only one click is required).

I have never had this problem, and I think it could be a Materialize problem. Before I count materialize out, though, I want to check with you guys and hear if I am possibly calling my JQuery functions wrong or something. Here is the code:

header.html:

<template name="header">
  <nav>
    {{> sideNav}}
    <div class="nav-wrapper">
      <a href="#" class="brand-logo center"><span class="light"></span>hamok</a>
      <ul id="nav-mobile" class="left">
        <li><a href="#" data-activates="slide-out" class="button-collapse show-on-large"><i class="mdi-navigation-menu"></i></a></li>
        <li><a href="#"><i class="mdi-action-search left"></i>Search</a></li>
      </ul>
      <ul id="nav-mobile" class="right">
        {{#if currentUser}}
          <li><a id="logout">Sign out</a></li>
        {{else}}
        <li><a class="modal-trigger-login" href="#loginModal">Account<i class="left mdi-action-account-circle"></i></a></li>
        {{/if}}
      </ul>
    </div>
  </nav>

  {{> loginModal}}
</template>

<template name="loginModal">
  <div id="loginModal" class="modal">
    <div class="modal-content">
      {{> atForm}}
    </div>
  </div>
</template>

<template name="sideNav">
  <ul id="slide-out" class="side-nav">
    <li><a href="#!">First Sidebar Link</a></li>
    <li><a href="#!">Second Sidebar Link</a></li>
  </ul>
</template>

header.js

Template['header'].helpers({

});

Template['header'].events({
  'click .modal-trigger-login': function() {
    $('.modal-trigger-login').leanModal();
  },

  'click #logout': function() {
    Meteor.logout();
  },

  'click .button-collapse': function() {
    $(document).ready(function(){
      $(".button-collapse").sideNav();
    });
  }
});

Thank you guys for taking a look!


Solution

  • What leanModal does is initializing the jQuery plugin, so it should be called inside of your template onRendered function, not when clicking on the modal trigger button.

    Template.header.onRendered(function(){
      this.$(".modal-trigger-login").leanModal();
    });
    

    You can remove your click .modal-trigger-login event : you currently need 2 clicks simply because the first one will just initialize the plugin.

    Likewise, your sideNav initialization call should be made in the onRendered lifecycle event :

    Template.header.onRendered(function(){
      this.$(".button-collapse").sideNav();
    });