Search code examples
htmlcsstwitter-bootstrapember.jshandlebars.js

How to highlight a list-item in an unordered list when clicked in Ember?


We are creating a way to filter in our jobs portal.

{{#rl-dropdown tagName="ul" class="dropdown-menu" closeOnChildClick="li"}}
   <li {{action 'filterWith' department 'all'}}>
        All
    </li>
    <li active=true {{action 'filterWith' department 'intern'}}>
        Intern
    </li>
    <li {{action 'filterWith' department 'newgrad'}}>
        New Grads
    </li>
    <li {{action 'filterWith' department 'entry'}}>
        Entry Level
    </li>
    <li {{action 'filterWith' department 'senior'}}>
        Senior
    </li>
{{/rl-dropdown}}

When a user clicks a <li>, it will call the function filterWith which filters either/or (AKA exactly one filter is applied at any time). We want whichever filter is clicked to be highlighted a different color from the rest.

Implementing this has been very difficult because we want to do it in a way that doesn't use jQuery (we have been having trouble with mixing jQuery and Ember together). We might be able to do it just with Bootstrap to do it if we knew how to.

Edit:

This is my Ember Controller (AKA where filterWith is defined).

export default Ember.Controller.extend({
    department: 'all',
    level: 'all',
    filteredPosts: Ember.computed('level', function() {
        var emberCont = this;
        return this.get('model').filter(function(item){
            var lvl = emberCont.get('level');

            // This should be refactored somehow
            if(lvl == 'all') {
                return true;
            }
            else if (lvl == item.get('level')) {
                return true;
            }

            return false;
        });
    }),


    actions: { 
        filterWith(dept, lvl) {
            this.set('department', dept);
            this.set('level', lvl);
        }
    }
});

I filter by two variables (level and filter). Department currently doesn't do anything so I suggest ignoring it.


Solution

  • Probably the action filterWith somehow should store the current filter value. Next you can the eq helper from ember-truth-helpers to do something like class="{{if (eq currentFilter 'intern') 'active'}}", which will give you the active class on the current filter. The rest is simple CSS.

    Checkout this twiddle for a working demonstration.


    The other thing you could do is to generate your filters dynamically, and then attach a boolean telling which one is active. This is a solution without a helper.