Search code examples
csshtmltwitter-bootstrapuser-experience

Switching states when button is clicked?


I'm stuck with a design/UX issue that I'm working on.

I have a button which says "No Filter" and if I click, I want it to change to "Reset" and clicking on reset should get me back to old state. (No filter) (Additionally, I'm changing the value in the dropdown if that helps)

What should I use to represent this behavior? (Switch, Button?) Kinda confused.

Code:

      <button type="button" class="btn btn-sm" id="removeDwell">
          <i id="removeDwell"></i> No filter
      </button>

enter image description here


Solution

  • I would suggest placing the both the button internal options in there at the start. Then use CSS and JS to toggle a class that hide/shows the relevant internals. Given that you mention you're changing the value inside the dropdown, i would assume you've probably already got a button .on('click') binding somewhere, this code would just extend that.

    By using the .btn-active-toggle and the internal .when-active or .when-inactive classes, you have the option to use this same logic in a number of places that you'd like to toggle the internal display of a button (or rather anything with the class of .btn-active-toggle). In terms of naming conventions, given bootstrap includes CSS for any .btn with the class .active, you may want to consider using a different class name than .active if you do not wish for this out-of-the-box styling; just update the JS and CSS below.

    Note: this solution is not the best from an accessibility point of view, as screen readers will read both internals, without knowing which is active. If this is important for you, consider similarly toggling aria values to specify which is active

    HTML

    <button type="button" class="btn btn-sm btn-active-toggle" id="removeDwell">
        <span class="when-active">  
            <i class="glyphicon glyphicon-remove"></i> No filter
        </span>
        <span class="when-inactive">    
            <i class="glyphicon glyphicon-refresh"></i> Reset
        </span>
    </button>
    

    CSS

    .btn-active-toggle.active .when-active,
    .btn-active-toggle .when-inactive{
        display:inline-block;
    }
    .btn-active-toggle.active .when-inactive,
    .btn-active-toggle .when-active{
        display:none;
    }
    

    JS

    $('#removeDwell').on('click', function(){
        $(this).toggleClass('active');
    })
    

    JSFIDDLE