Add / Remove class on click


#1

Hey,

It’s maybe a newbie question but I’m looking for a solution since this morning.

I’ve two inputs, and I want to add or remove a class when the focus, or the blur is triggered. But when I try do do this, it seems that the DOM isn’t loaded and the inputs doesn’t exist.

Ember.$(".input-group.transparent").children('input').blur(function () {
       Ember.$(this).parent().children('.input-group-addon').removeClass('input-focus');
});

Ember.$(".input-group.transparent").children('input').focus(function () {
       Ember.$(this).parent().children('.input-group-addon').addClass('input-focus');
});
<div class="input-group transparent">
                <span class="input-group-addon">
                  <i class="fa fa-key"></i>
                </span>
                {{input type="password" value=model.password class="form-control" placeholder="Mot de passe"}}
              </div>

I’ve tried with renderTemplate, init but nothing work.

Anyone can help me ?

Cheers.


#2

Here in Ember land, we frown upon relying on jQuery to do thing. In fact, starting from Ember 2.9, jQuery became optional with ember-native-dom-event-dispatcher

Everything in Ember is all about Route and Template, with a little Component sprinkled here and there.

Route#renderTemplate doesn’t ACTUALLY renders the template. It schedules the rendering of templates. It’s the hook that let you manually invoke Route#render. Again, this doesn’t actually renders it. It does the scheduling.

The right design for this is to use the built-in {{input}} helper to dispatch action to your controller. Use controller’s action handler to set a property there, then bind the property down to the template. We call it DDAU (Data Down, Actions Up).

// app/controllers/application.js
export default Ember.Controller({
  actions: {
    focus(state) {
      this.set('focused', state);
    }
  }
});
{{! app/controllers/application.hbs }}

{{input focus-in=(action "focus" true) focus-out=(action "focus" false)}}

<div class="input-group-addon {{if focused 'input-focus'}}"></div>
<div class="input-group-addon {{if focused 'input-focus'}}"></div>
<div class="input-group-addon {{if focused 'input-focus'}}"></div>
<div class="input-group-addon {{if focused 'input-focus'}}"></div>

#3

I wasn’t thinking that way, but is much more beautiful to do this like this actually.

I’ll try this and i’ll keep you in touch, thanks for everything @lightblade !


#4

Hey @lightblade, I tried yesterday and it’s working juste fine, I made some adjustments for my needs but the logic is absolutely amazing.

Thanks


#5

Hi @lightblade,

Very nice explained, and it is helped so much to finish my task. Is the “focus-in” is inbuilt attribute in ember for {{input}} ?


#6

Why the extra work in Ember when CSS can do that for you:

{{input value=myValue class="my-input"}}
.my-input {
  border: thin solid black;
}
.my-input:focus {
  border-color: red;
}