Search code examples
javascriptfilteringgetuikit

UIkit 3's Filter component: Set active filter with URL hash - unable to change active filter with JS


I'm trying to pass a hash to an URL to set a UIkit filter.

<div uk-filter="target:.js-filter">
    <ul>
        <li class="uk-active" uk-filter-control><a href="#">All</a></li>
        <li uk-filter-control="filter:[data-color='blue'];"><a href="#"></a></li>
        <li uk-filter-control="filter:[data-color='white'];"><a href="#"></a></li>
    </ul>
    <ul class="js-filter">
        <li data-color="blue"></li>
        <li data-color="white"></li>
    </ul>
</div>

So, for example, if I go to http://example.com/#white the thing shows only the white items (and the "white" filter control is active).

I couldn't find any clear example about how to achieve this with UIkit 3 (This one is about UIkit 2). Documentation seems unclear for a noob like me, for it's unclear what target and selActive options are refering to. However, I'm trying with the following:

<script>
document.addEventListener("DOMContentLoaded", function(event){
    hash = document.location.hash;
    console.log("Hash: " + hash);

    if ( hash !== "" ) {
        var filter = document.querySelector('.js-filter');

        UIkit.filter( filter, {
            target: 'li [data-color:' + hash + ']',
            selActive: true,
        });
    }
});
</script>

But this throws a "Uncaught TypeError: Cannot read property 'children' of null" error.

Any help would be appreciated. :)


Solution

  • <div uk-filter="target:.js-filter">
    <ul id="filter-bar">
        <li class="uk-active" uk-filter-control><a href="#">All</a></li>
        <li uk-filter-control="filter:[data-color='blue'];"><a href="#"></a></li>
        <li uk-filter-control="filter:[data-color='white'];"><a href="#"></a></li>
    </ul>
    <ul class="js-filter">
        <li data-color="blue"></li>
        <li data-color="white"></li>
    </ul>
    

          document.addEventListener("DOMContentLoaded", function(event){
            hash = document.location.hash;
            console.log("Hash: " + hash);
    
            if ( hash !== "" ) {
                var filter = document.querySelector('.js-filter');
                var filterBar= document.querySelector('#filter-bar');
                var activeFilter= document.querySelector('li [data-color:' + hash + ']');
                UIkit.filter( filterBar, {
                    target: filter,
                    selActive: activeFilter,
                });
            }
        });
    

    I'm hear too late) But try this code. You need to pass your filter component first not your list.