thomas samot
thomas samot

Reputation: 29

Sorting elements with jQuery using data attributes

Just to let you know, I'm a rookie. I try to programm a certain function for the menu-navigation on my website. (http://thomasmedicus.at/)

I want visitors on my website to be able to sort my projects either by "date" or by "relevance". I created this image so you can understand me better: preview

in the first image the projects are sortet by relevance. therefor "date" is striked trough. when you now click on the stricked trough "date" the order of the projects (2, 1, 3) changes. what also happens is that "relevance" is strickt trough and "date" not anymore. of course this should also work the other way round when you then click on "relevence" again. i hope you get the idea!?

i managed to create this badly programmed script, but what isnt programmed here is the striking through:

<html>
<head>
<style type="text/css">
<!--
body {
	text-align: left;
}
#fullDescrip {
	width: 450px;
	height: 200px;
	border: solid #000000 2px;
	margin: 0 auto;
	text-align: justify;
	padding: 20px;


}
#prodContainer .products {
	margin: 10px;
	border: solid #AAAAAA 1px;
	width: 100px;
	height: 100px;


}
#prodContainer2 .products {
	margin: 10px;
	border: solid #AAAAAA 1px;
	width: 100px;
	height: 100px;

}
-->
</style>
<script>
	var rand = Math.floor(Math.random() * 2);//the number here must be the total number of products you have listed
	var prod = new Array();
	prod[0] = "<width='100' height='100'>changed here!";
	prod[1] = "<width='100' height='100'>changed again!";

	function loadProd(content){
		document.getElementById('fullDescrip').innerHTML = content;
	}
</script>





</head>

<body>
<div id="fullDescrip">
<script>
document.getElementById('fullDescrip').innerHTML = prod[rand];

</script>
</div>

        <table id="prodContainer">
	<tr>
     	<td>
        <div id="prod1" class="products" onClick="loadProd(prod[0])">
        button 1
        </div>
        </td>
        <td>

        <table id="prodContainer2">
	<tr>
    	<td>
        <div id="prod2" class="products" onClick="loadProd(prod[1])">
        button 2
        </div>
        </td>


        
</body>
</html>

it would be awesome if you can help me here. since i am no programmer i'm not able to do it on my own...

thanks, tom

Upvotes: 1

Views: 1013

Answers (2)

halfzebra
halfzebra

Reputation: 6797

I think you should leave vanilla JavaScript for later and use jQuery library to make your life much easier. Your website is already using it, so you don't have to adjust anything.

Here is a good example of sorting with jQuery jQuery sort elements using data id

All you need is to provide some criteria for sorting, the example above relies on data-attribute, which is really handy for this kind of functionality.

/** 
 * This function returns a callback for data-attribute based sorting.
 *
 * @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 $(a).data(sortCriteria) - $(b).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-weight' at the start.
highlightActive('.btn-sort-weight', 'btn-sort--active');
sortByDataAttr('weight', '.item', '.list');

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

$('.btn-sort-index').on('click', function() {
  highlightActive(this, 'btn-sort--active');
  sortByDataAttr('index', '.item', '.list')();
});
.btn {
  text-decoration: line-through;;
}

.btn-sort--active {
  text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-sort-weight">Sort by weight</button>
<button class="btn btn-sort-index">Sort by index</button>
<ul class="list">
  <li class="item" data-index="133" data-weight="5">First - weight: 5 - index: 133</li>
  <li class="item" data-index="2" data-weight="1">Second - weight: 1 - index: 2</li>
  <li class="item" data-index="87" data-weight="16">Third - weight: 16 - index: 87</li>
</ul>

Upvotes: 1

Sachin Kanungo
Sachin Kanungo

Reputation: 1064

Refer to this site for sorting algorithms http://www.sorting-algorithms.com/. You should go by scalability to overcome future problems with sorting.Array.sort() is helpful. Check this fiddle http://jsfiddle.net/BF8LV/2/

    function sortAscending(data_A, data_B)
{
    return (data_A - data_B);
}
var array =[ 9, 10, 21, 46, 19, 11]
array.sort(sortAscending) 
alert(array);

Upvotes: 0

Related Questions