thomas samot
thomas samot

Reputation: 29

jquery button with cookies to remember menu setting after refresh

On my webpage visitors can sort the menu either by "relevance" or "date". But when one chooses "relevance" and loads a new page, the selection goes back to "date". As far as i found out, it is not possible to solve this problem without cookies!? So i uploaded "jquery-1.11.3.min.js" and "jquery.cookie.js" to my page.

Can I start to activate cookies for the button now? How can I save cookies so that the option stays after the refresh? Since 'date' is the default option I actually only need to save cookies when people select 'relevance'. What would be the code to reach my goal?

Here is the code I use for my menu:

/** 
 * Hier beginnt im JSFiddle der JavaScript Bereich
 *
 * @param sortCriteria
 *   Name of the data-attribute for sorting.
 * @param itemsToSort
 *   A string selector for items for sorting.
 * @param container
 *   A container to put items.
 * @returns {Function}
 */
var sortByDataAttr = function (sortCriteria, itemsToSort, container) {
    return function () {

        // Grab all the items for sorting.
        var $collection = $(itemsToSort);

        // Sort them and append in to container.
        $collection.sort(function (a, b) {
            return $(b).data(sortCriteria) - $(a).data(sortCriteria)
        }).appendTo($(container));
    };
},


/**
 * Remove class from all elements and apply to current.
 *
 * @param current
 *   HTML node to apply class.
 * @param activeClass
 *   Active-state string class.
 */
highlightActive = function (current, activeClass) {
    $('.' + activeClass).removeClass(activeClass);
    $(current).addClass(activeClass);
};

// Sort by 'data-date' at the start.
highlightActive('.btn-sort-date', 'btn-sort--active');
sortByDataAttr('date', '.item', '.list');

$('.btn-sort-date').on('click', function () {
    highlightActive(this, 'btn-sort--active');
    sortByDataAttr('date', '.item', '.list')();
});

$('.btn-sort-relevance').on('click', function () {
    highlightActive(this, 'btn-sort--active');
    sortByDataAttr('relevance', '.item', '.list')();
});
// Hier endet im JSFiddle der JavaScript Bereich
<!-- Im JSFiddle startet der html Bereich hier -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<aside id="nav_menu-5" class="widget-1 widget-first widget-odd widget widget_nav_menu">
    <div class="menu-projects-container">
        <ul id="menu-projects" class="menu">

<div style="color:#A4A4A4" class="daterel"> 
<span class="btn btn-sort-date"><i>date</i></span>
<span>|</span>

                <span class="btn btn-sort-relevance"><i>relevance</i></span>
</div>

            <div class="projects">


<b>PROJECTS</b>

           
            </div>
            <div class="list">
                     <li id="menu-item-649" class="item" data-relevance="11" data-date="2015.6"><a href="http://thomasmedicus.at/brickstone-blues/">brickstone blues</a>
<span style="color:#A4A4A4">video</span>
                         
                <li id="menu-item-649" class="item" data-relevance="7" data-date="2015.5"><a href="http://thomasmedicus.at/copypaste/">copy&#038;paste</a>
<span style="color:#A4A4A4">installation</span>

                    <li id="menu-item-649" class="item" data-relevance="6" data-date="2015.4"><a href="http://thomasmedicus.at/zebral-fluids/">zebral fluids</a>
<span style="color:#A4A4A4">gif</span>

                        <li id="menu-item-649" class="item" data-relevance="8" data-date="2015.3"><a href="http://thomasmedicus.at/fried-egg-variation/">fried egg variation</a>
<span style="color:#A4A4A4">glass</span>

                        </li>
                        <li id="menu-item-649" class="item" data-relevance="8" data-date="2015.2"><a href="http://thomasmedicus.at/bearrr/">bearrr&#8230;</a>
<span style="color:#A4A4A4">illustration</span>

                        </li>
                        <li id="menu-item-649" class="item" data-relevance="7" data-date="2015.1"><a href="http://thomasmedicus.at/glass-ribbon/">glass ribbon</a>
<span style="color:#A4A4A4">glass</span>

                        </li>
                        <li id="menu-item-649" class="item" data-relevance="13" data-date="2014.5"><a href="http://thomasmedicus.at/emulsifier/">emulsifier</a>
<span style="color:#A4A4A4">sculpture</span>

                        </li>
                        <li id="menu-item-649" class="item" data-relevance="9" data-date="2014.4"><a href="http://thomasmedicus.at/black-holes/">black holes</a>
<span style="color:#A4A4A4">illustration</span>

                        </li>
                        <li id="menu-item-649" class="item" data-relevance="7" data-date="2014.3"><a href="http://thomasmedicus.at/this/">**** this!</a>
<span style="color:#A4A4A4">concept</span>

                        </li>
                        <li id="menu-item-649" class="item" data-relevance="10" data-date="2014.2"><a href="http://thomasmedicus.at/heads/">heads</a>
<span style="color:#A4A4A4">mask</span>

                        </li>
                        <li id="menu-item-649" class="item" data-relevance="5" data-date="2014.1"><a href="http://thomasmedicus.at/staining-glass/">staining glass</a>
<span style="color:#A4A4A4">glass</span>

                        </li>
                        <li id="menu-item-649" class="item" data-relevance="11" data-date="2013.2"><a href="http://thomasmedicus.at/fishbird/">fish&#038;bird</a>
<span style="color:#A4A4A4">flipbook</span>

                        </li>
                        <li id="menu-item-649" class="item" data-relevance="6" data-date="2013.1"><a href="http://thomasmedicus.at/faces/">faces</a>
<span style="color:#A4A4A4">sculpture</span>

                        </li>
            </div>
<!-- Im JSFiddle geht der html Bereich bis hier -->

thank you for your support!

Upvotes: 1

Views: 895

Answers (3)

Amin Jafari
Amin Jafari

Reputation: 7207

you need to do this:

Add the cookie

$('.btn-sort-date').on('click', function () {
    highlightActive(this, 'btn-sort--active');
    sortByDataAttr('date', '.item', '.list')();
    $.cookie('sort','date');
});

$('.btn-sort-relevance').on('click', function () {
    highlightActive(this, 'btn-sort--active');
    sortByDataAttr('relevance', '.item', '.list')();
    $.cookie('sort','relevance');
});

And check the cookie on page load

if (typeof $.cookie('sort') == 'undefined'){
    $.cookie('sort','date');
    highlightActive('.btn-sort-date', 'btn-sort--active');
    sortByDataAttr('date', '.item', '.list');
}
else{
    var sort=$.cookie('sort');
    highlightActive('.btn-sort-'+sort, 'btn-sort--active');
    sortByDataAttr(sort, '.item', '.list');
}

So your final code would be

/** 
 * Hier beginnt im JSFiddle der JavaScript Bereich
 *
 * @param sortCriteria
 *   Name of the data-attribute for sorting.
 * @param itemsToSort
 *   A string selector for items for sorting.
 * @param container
 *   A container to put items.
 * @returns {Function}
 */
var sortByDataAttr = function (sortCriteria, itemsToSort, container) {
    return function () {

        // Grab all the items for sorting.
        var $collection = $(itemsToSort);

        // Sort them and append in to container.
        $collection.sort(function (a, b) {
            return $(b).data(sortCriteria) - $(a).data(sortCriteria)
        }).appendTo($(container));
    };
},


/**
 * Remove class from all elements and apply to current.
 *
 * @param current
 *   HTML node to apply class.
 * @param activeClass
 *   Active-state string class.
 */
highlightActive = function (current, activeClass) {
    $('.' + activeClass).removeClass(activeClass);
    $(current).addClass(activeClass);
};

if (typeof $.cookie('sort') === 'undefined'){
    $.cookie('sort','date');
    highlightActive('.btn-sort-date', 'btn-sort--active');
    sortByDataAttr('date', '.item', '.list');
}
else{
    var sort=$.cookie('sort');
    highlightActive('.btn-sort-'+sort, 'btn-sort--active');
    sortByDataAttr(sort, '.item', '.list');
}

$('.btn-sort-date').on('click', function () {
    highlightActive(this, 'btn-sort--active');
    sortByDataAttr('date', '.item', '.list')();
    $.cookie('sort','date');
});

$('.btn-sort-relevance').on('click', function () {
    highlightActive(this, 'btn-sort--active');
    sortByDataAttr('relevance', '.item', '.list')();
    $.cookie('sort','relevance');
});

// Hier endet im JSFiddle der JavaScript Bereich

UPDATE:

changed the way the functions were defined and it works as expected: DEMO

/** 
 * Hier beginnt im JSFiddle der JavaScript Bereich
 *
 * @param sortCriteria
 *   Name of the data-attribute for sorting.
 * @param itemsToSort
 *   A string selector for items for sorting.
 * @param container
 *   A container to put items.
 * @returns {Function}
 */
function sortByDataAttr(sortCriteria, itemsToSort, container) {
        alert('inside');

        // Grab all the items for sorting.
        var $collection = $(itemsToSort);

        // Sort them and append in to container.
        $collection.sort(function (a, b) {
            return $(b).data(sortCriteria) - $(a).data(sortCriteria)
        }).appendTo($(container));
};


/**
 * Remove class from all elements and apply to current.
 *
 * @param current
 *   HTML node to apply class.
 * @param activeClass
 *   Active-state string class.
 */
function highlightActive(current, activeClass) {
    $('.' + activeClass).removeClass(activeClass);
    $(current).addClass(activeClass);
};

if (typeof $.cookie('sort') === 'undefined'){
    alert($.cookie('sort'));
    $.cookie('sort','date');
    highlightActive('.btn-sort-date', 'btn-sort--active');
    sortByDataAttr('date', '.item', '.list');
}
else{
    alert($.cookie('sort'));
    var sort=$.cookie('sort');
    highlightActive('.btn-sort-'+sort, 'btn-sort--active');
    sortByDataAttr(sort, '.item', '.list');
}

$('.btn-sort-date').on('click', function () {
    highlightActive(this, 'btn-sort--active');
    sortByDataAttr('date', '.item', '.list')();
    $.cookie('sort','date');
});

$('.btn-sort-relevance').on('click', function () {
    highlightActive(this, 'btn-sort--active');
    sortByDataAttr('relevance', '.item', '.list')();
    $.cookie('sort','relevance');
});

// Hier endet im JSFiddle der JavaScript Bereich

Upvotes: 0

user4227915
user4227915

Reputation:

Using HTML5 localStorage should look like follows:

$(document).ready(function(){

    $('.btn-sort-date').on("click", function(){
        localStorage.setItem("selected_item", "date");
    });

    $('.btn-sort-relevance').on("click", function(){
        localStorage.setItem("selected_item", "relevance");
    });

    var selected_item = localStorage.getItem("selected_item");

    if (selected_item) {
         sortByDataAttr(selected_item, '.item', '.list');
    }

});

Run it at the end of the page..

Hope it helps.

Upvotes: 0

Dorian
Dorian

Reputation: 211

If you want to use cookies, you should add the following after sortByDataAttr('relevance', '.item', '.list')(); :

$.cookie('sortby', 'relevance', {expires:30});

And this at the beginning of you javascript :

$(document).ready(function() {
    if ('relevance' == $.cookie('sortby')) {
        sortByDataAttr('relevance', '.item', '.list')();
    } else {
        sortByDataAttr('date', '.item', '.list')();
    }
});

It'll look for a cookie with the name "sortby" and if the value is "relevance" it'll sort the list accordingly.

Upvotes: 1

Related Questions