How to handle a CSS property of clicked object?

Hi people! Tell me please, how to handle onclick action by ID. For example, i’ve something in hbs template:

<button id="myButton" {{action "myAction"}} >OK</button>

it has CSS:

button {color: "red";}

How to do two things by onclick action:

  1. Set property to clicked object (only to clicked), eg to set CSS colour “green”,
  2. Get some property of clicked (eg CSS colour), and console log or alert.

Thanks in advance!

I think this is covered by example in my answer to your other question.

But in general: when you are writing an Ember app (or really any kind of modern framework, including Vue or React too), you don’t store your state in the DOM. Meaning, you don’t ask the button what color it is. You tell it what color to be.

// in your component's template
<button style="background-color: {{this.preferredButtonColor}}" {{action this.changeColor}} />
// in your component's javascript
changeColor() {
  if (this.preferredButtonColor === 'red') {
    this.set('preferredButtonColor', 'blue');
  } else {
    this.set('preferredButtonColor', 'red');
  }
}

It’s quite rare to use Element id to locate things when writing apps this way. It makes your components less reusable, because ids are effectively global variables that can easily collide with each other.

2 Likes