zenben1126 zenben1126 - 5 months ago 60
Javascript Question

How to hide/show element in Meteor?

In my Meteor app I have a template with two divs: register and login. The code is as follows:

<div class="login">
<h1> Log in. </h1>
<a href"#">Create an account</a>
</div>

<div class="register">
<h1> Register. </h1>
<a href"#">Log in</a>
</div>


At first, the page should display the "login" div (which will eventually have a form in it) and the "register" div will be hidden from view. However, when I click "Create an account," the "login" div should disappear, and the "register" div should appear. At this point, if I click on "Log in" the reverse should happen.

Essentially, I just want to be able to switch between the login and register forms on the same page. I have tried this using {{#if}} and a click event, but this was not successful.

Anyone have an idea of how to do this?

Answer

There is a easy solution and a hardcode solution to achieve this.

The easy solution its use the accounts-ui package, and just use the

{{> loginButtons}} helper into the HTML, this actually have the expected behavior you wants.

And the hard way

On the hard way exists 2 possible solutions, using simple jQuery code, and Css. like this.

jQuery and CSS solution

Using the Same HTML you have on the example, use this 2 events handlers.

Template.example.events({
  'click #aRegister':function(){
    $(".login").css('visibility', 'hidden');
    $(".register").css('visibility', 'visible');

    },
     'click #aLogin':function(){
    $(".register").css('visibility', 'hidden');
     $(".login").css('visibility', 'visible');
    }
  })

And this .css

.register{
    visibility: hidden;
  }

Here is the MeteorPad

Meteor Way (using Sessions and #if)

First using the same 2 events we use some Sessions Variables, to set to true/false the value of the session, like this.

Template.example.events({
  'click #aRegister':function(){
  Session.set('showRegister',true);
    },
     'click #aLogin':function(){
    Session.set('showRegister',false);
    }
  })

Now on the HTML we use the {{#if}}

<template name="example">
{{#if showTheRegisterDiv}}
  <!-- Here if the Session returns its == true this part of the template will be rendered -->
  <div class="register">
    <h1> Register. </h1>
    <a href="#" id="aLogin">Log in</a>
  </div>
 {{else}}
  <!-- or if its == false we render this part -->
  <div class="login">
    <h1> Log in. </h1>
    <a href="#" id="aRegister">Create an account</a>
  </div>
{{/if}}
</template>

And this finally works thanks to this template helper.

Template.example.helpers({
    showTheRegisterDiv:function(){
        return Session.get('showRegister')
    }
})

Here is the MeteorPad