AMP: Toggle CSS Class

1.3k Views Asked by At

I am generating an amp template and I have a button that toggles the visibility of an amp-sidebar. The code is as follows:

<button class="button .closed icon" on='tap:sidebar1.toggle'></button>

The side-bar toggles as expected. However, I also want to the icon displayed to be changed depending on the state (open or closed).

I have the two classes for doing so:

  • button .closed (hamburger menu icon)

  • button .open (cross)

The shared class "icon" should remain the same between the two. I also want to keep the 'tap:sidebar1.toggle' so the menu will still toggle.

1

There are 1 best solutions below

0
Chris Aby Antony On BEST ANSWER

One way of achieving this would be by using an amp-state to keep track of whether the sidebar is open or closed. Then you can bind the button's class using this state to style it accordingly.

Initialise an amp-state like follows :

<amp-state id = "sbOpen">
    <script type = "application/json">
        false
    </script>
</amp-state>

and now change your sidebar code as follows :

<amp-sidebar

 on="sidebarOpen:AMP.setState({sbOpen});sidebarClose:AMP.setState({sbOpen})" 

and finally your button tag should be something like this :

<button class="button closed icon" on='tap:sidebar1.toggle'
        [class]=" 'button icon ' + (sbOpen?'open':'closed) "></button>