Change DIV class on click action


I want to change the DIV class base on CLICK action. I am trying to make a floating sidebar like this

This demo has only three lines of code for toggle-ing the class.

    $("#menu-toggle").click(function(e) {

I want to achive same thing but in ember way. Below is my HTML code:

<script type="text/x-handlebars" id="cards/index">
        <button class="pull-left btn btn-default" data-target="#main_menu" {{action 'changeClass'}}>
           <img src="images/icons/menu_tablet.png" class="main_menu"/>

Now I do not know how can I use the action to change the class in WRAP div. I will really appreciate any help regarding this issue.


Something like this?

<div {{bind-attr class=":wrapper isActive:active"}}>
    <button class="btn btn-default" {{action 'changeClass'}}>Make Active</button>

And then, the code of your action:

changeClass: function() {
  this.set('active', !this.get('active'));

Your class is binded to the active parameter from your controller, which you toggle when clicking. Therefore, that class will be added and removed when the action is executed.


Hi Dmathieu, Thanks for your input. Firstly, the bind-attr will go to WRAP div which is in a separate handelbar template (please see the code above) and the button with action is in another handlebar template. Secondly you not mentioned where shall I place the code for action? In controller like this;

Cards.CardsController = Ember.ObjectController.extend({
    changeClass: function() {
        this.set('active', !this.get('active'));

but anyway I tried to run the code after placing the action code into Controller I get this error: Uncaught Error: Nothing handled the event ‘changeClass’.

Can you give any idea what is going on? Does it mean I need to define a model for this action?


Actions should be placed in an actions hash on the controller, so:

  actions: {
    changeClass: function () {
      // ..

Also, remember that actions do not return anything…

You can also use this.toggleProperty('isActive') to toggle boolean property values.


How to do the same for multiple items like below

{{#each options as |option| }}

<div {{action 'toggleClass'}} class = ''> {{option}}</div>

<input type='text' class='hide'>



Perhaps a component:

{{#each options as |option| }}
  {{my-component option=option}}

And then handle the click logic inside it.


Make it this way.

{{#toggle-component toggleClass=toggleClass as  |compObj| }}
 <div class="wrapper {{if compObj.isActive 'active'}} ">

In toggle-component.js

toggleClass: Ember.on('click', function () {