u111937
u111937

Reputation: 287

Adding 'active' class with jQuery doesn't work due to specificity

I've created a navigation that acts as filters and grabs things from Firebase according to what filter/item in the navigation is clicked on.

The filters work great, however I am trying to get it to display an active class when a user clicks on a filter. My setActive() function works on adding the active class to the items respectively, however the active class is not working due to specificity.

I'm also using LESS and would like to understand a better way on adding &:active instead of just a standalone active class.

JS

//Sets the Active Class once a filter has been selected

function setActive() {
    $('#filters').on('click','li',function(){
        $('#filters li.active').removeClass('active');
        $(this).addClass('active');
    });
}

setActive();

// A click functions for each filter, that sets filterToSelect for Firebase respectively

$('body').on('click', '#filter-storage', function(e) {
    e.preventDefault();

    filterToSelect = "storage";
    setFilter(filterToSelect);
});

HTML

<div id="filters" class="filters">
                <ul>
                    <li id="filter-all">All Categories</li>
                    <li id="filter-browser">Browser</li>
                    <li id="filter-chat">Chat</li>
                    <li id="filter-email">Email</li>
                    <li id="filter-encryption">Encryption</li>
                    <li id="filter-os">os</li>
                    <li id="filter-storage">Storage</li>
                </ul>
            </div>

LESS

.filters {
    cursor: pointer;
    padding-bottom: 30px;

    ul {
        list-style-type: none;
        margin: 0;
        padding: 0;

        li {
            display: inline-block;
            padding-right: 15px;
            color: #717171;
            font-size: 13px;
            font-weight: 600;
            letter-spacing: 1px;
            text-transform: uppercase;

            &:last-child { padding-right: 0; }

            &:hover {
                color: #424141;
            }

            &:active {
                color: #424141;
            }
        }
    }
}

EDIT

Working site on github pages - https://onehunnid.github.io/psb/

Repo - https://github.com/OneHunnid/psb

Upvotes: 1

Views: 635

Answers (1)

Stephen Thomas
Stephen Thomas

Reputation: 14063

The problem isn't specificity. You've written your LESS incorrectly. Instead of

&:active {
    color: #424141;
}

You probably want

&.active {
    color: #424141;
}

That's because you're adding a class, not relying on a link :active state (which is only valid for <a> tags anyway)

Upvotes: 1

Related Questions