amp bind change state with button

2.3k Views Asked by At

I have this code:

 <style amp-custom>

  .plus, .mius {
    width: 50px;
    height: 50px;
   }

   .plus {background-color: blue;}
   .mius {background-color: green;}

</style>
<body>
<amp-state id="text">
  <script type="application/json">
    {
      "textspan1": "plus"
    }
  </script>
</amp-state>

     <p [text]="text.textspan1=='plus'?'mius':'plus'" 
     [class]="text.textspan1=='plus'?'mius':'plus'" class="plus"></p>

    <button on="tap:AMP.setState({textspan1: (textspan1 == 'plus' ? 'mius' : 
    'plus')})">puls</button>

</body>

I want to change the state of

when the button is clicked but it happens one time. I mean, if i click once the

the color is changed but when i click second time the color is not changed.

Do you have any idea to change the color all the time when the button is clicked?

3

There are 3 best solutions below

0
On BEST ANSWER

I found the solution. Just remove the object 'text' on p tag. See below:

   <p [text]="textspan1=='plus'?'mius':'plus'" 
      [class]="textspan1=='plus'?'mius':'plus'" class="plus"></p>
2
On

Would this code work?

function changeColor() {
  runFunction0 = runFunction;
  runFunction = runFunction0 + 1;

  if (runFunction / 2 != Math.round(runFunction / 2)) {
    document.getElementById("area").className = "mius";
  } else
  if (runFunction / 2 == Math.round(runFunction / 2)) {
    document.getElementById("area").className = "plus";
  }

}

var runFunction0
var runFunction = 0;
.plus,
.mius {
  width: 50px;
  height: 50px;
}

.plus {
  background-color: blue;
}

.mius {
  background-color: green;
}
<body>
  <amp-state id="text">
    <script type="application/json">
      {
        "textspan1": "plus"
      }
    </script>
  </amp-state>

  <p id="area" [text]="text.textspan1=='plus'?'mius':'plus'" [class]="text.textspan1=='plus'?'mius':'plus'" class="plus"></p>

  <button on="tap:AMP.setState({textspan1: (textspan1 == 'plus' ? 'mius' : 
    'plus')})" onclick="changeColor();">puls</button>

</body>

0
On

You could also do something like this:

<button on="tap:AMP.setState({toggled: !toggled})">toggle</button>

The state negates itself every time it's clicked.

Then you can just listen to the state like a boolean variable and bind your classes or texts or anything else possible.

<p [text]="toggled ? 'mius' : 'plus'" 
   [class]="toggled ? 'mius' : 'plus'" class="plus">plus</p>

Note: You don't have to initialize every state with an <amp-state> tag. It's only necessary if you need access to the stored values even without any interaction.