Change DIV class on click action


#1

I want to change the DIV class base on CLICK action. I am trying to make a floating sidebar like this http://startbootstrap.com/templates/simple-sidebar.html

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

<script>
    $("#menu-toggle").click(function(e) {
        e.preventDefault();
        $("#wrapper").toggleClass("active");
    });
    </script>

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

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

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.


#2

Something like this?

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

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.


#3

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?


#4

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

Em.ObjectController.extend({
  actions: {
    changeClass: function () {
      // ..
    }
  }
});

Also, remember that actions do not return anything…

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


#5

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'>

{{/each}}


#6

Perhaps a component:

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

And then handle the click logic inside it.


#7

Make it this way.

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

In toggle-component.js

toggleClass: Ember.on('click', function () {
  this.toggleProperty('isActive');
})