BlowFish BlowFish - 1 month ago 14
Javascript Question

Count Clicks and Sort Tags by the clicks Javascript

I have a list of tags, this list is populated by a database and MVC.
I have a razor code that pulls in each tag for sorting purposes.
Recently I was asked to have each tag track how many times it's clicked, and then reorder the tags displayed by how many times the tags have been clicked.

Here is my razor code for the list of tags

<ul class="pills" id="tags">
@foreach (var tag in tags)
{
<li><a href="#" data-tag-selector="@tag">@tag</a></li>
}
</ul>


I tried
var clicks = 0 and adding onclick=clicks++ to the a href
but I think I might be on the wrong track. I think Javascript might be my go to.

Answer

Here's a simple solution that will work until you refresh the browser:

HTML partial:

<ul class="pills" id="tags">
    <li data-click-count=0>tag1</li>
    <li data-click-count=0>tag2</li>
    <li data-click-count=0>tag3</li>
</ul>

jQuery snippet

When a tag is clicked, increment that tag's click count and then re-sort the tag list.

var $tags = $('#tags').find('li');

$tags.click(function (e) {
  // Get the click count for the tag that was just clicked
  var tagCount = $(e.currentTarget).attr('data-click-count');

  $(e.currentTarget).attr('data-click-count', parseInt(tagCount) + 1);

  // Remove tags from the DOM but keep data so you can reorder them
  $tags.detach();

  // Sort the tags by click count
    $tags.sort(function(a, b) {
        return $(b).attr('data-click-count') - $(a).attr('data-click-count');
  });

  // Insert them back into the unordered list DOM element
  $('#tags').html($tags);

});

JSFiddle demo: https://jsfiddle.net/adamgibbons/ohos5a17/