Live sets of tags, Leak-safe

by b9chris

HTML

<div><button>Number of 3s</button> <span id=number></span></div>

CSS

body {
    font: 10pt Verdana;
}

i {
    display: block;
    float: left;
    font-style: normal;
    width: 20px; height: 20px;
    text-align: center; vertical-align: middle;
    border: 1px solid #888;
    margin: 2px;
    cursor: pointer;
    -moz-user-select: none; 
    -khtml-user-select: none; 
    -webkit-user-select: none;
}

i.c0 {
    color: #c00;
    background: #fcc;
}
i.c1 {
    color: #a80;
    background: #ff8;
}
i.c2 {
    color: #0a0;
    background: #bfb;
}
i.c3 {
    color: #00c;
    background: #ccf;
}

JavaScript

for(var i = 0; i < 100; i++) {
    $('body').append('<i class=c0>0</i>');
}

var sets = [
    // Our 4 sets
    $('i.c0'), $('i.c1'), $('i.c2'), $('i.c3')
];

$('body').on('click', 'i', function() {
    var index = this.className.substr(1) - 0;
    var oldIndex = index;
    index = (index + 1) % 4;
    this.className = 'c' + index;
    $(this).text(index);
    
    // Maintain tag sets that leverage jQuery's garbage collection
    sets[oldIndex] = sets[oldIndex].not(this);
    sets[index] = sets[index].add(this);
});

$('button').click(function() {
    $('#number').text(sets[3].length);
});