I have this script:
JS
// A & B is needed
var needed = ["#n01", "#n03"];
// always holds what the user has clicked
var user = [];
// needed + user
var mixed = [];
// takes care of highlighting clicked letters &
// updating the user array
function hilit ( elem, cssClass ) {
$( elem ).click( function () {
if( $( this ).hasClass( cssClass )){
//remove from array "highlighted"
user.splice( $.inArray( "#" + $( this ).attr( "id" ), user ), 1 );
$( this ).removeClass( cssClass );
} else {
// add to array array "highlighted"
user.push( "#" + $( this ).attr( "id" ) );
$( this ).addClass( cssClass );
}
});
}
// is something wrong here? it works locally...
$("#lorem").on("click", function() {
// merging -> needed + user
mixed = $.merge(needed, user);
// removing duplicates
var map = new Object();
for ( var i = 0; i < mixed.length; i++ ) {
if (map[mixed[i]] === undefined ){
map[mixed[i]] = 1;
}
else{
map[mixed[i]]++;
}
}
// result = letters the user didn't click
var result = new Array();
for( var i = 0; i < mixed.length; i++ ){
if( map[mixed[i]] > 1 ){
//do nothing
}
else{
result.push(mixed[i]);
}
}
)};
hilit (".letter", "color");
Test case is here (thank you, CD..!): http://jsfiddle.net/uDsum/2
HTML
<p id="lorem">
<span class="letter" id="n01">A</span>
<span class="letter" id="n02">B</span>
<span class="letter" id="n03">C</span>
</p>
CSS
body {
font-size: 160px;
font-weight: bold;
}
.letter {
cursor: pointer;
}
.color {
background: red;
}
Description
Every letter inside the paragraph #lorem is wrapped in a span .letter. When .letter is clicked, it is checked if the class .color is present. If so, .color is removed and the corresponding ID is removed from the array user. Otherwise color is added and the the id is pushed into user.
There are thee Arrays: needed, user and mixed.
needed holds the IDs that the user needs to click. user holds the IDs the user has clicked. mixed is user and needed merged.
With every click, needed and user are merged into mixed. The result is that mixed holds some IDs twice. Then these duplicates are filtered out, leaving the IDs of elements the user should have clicked, but didn’t click in the array result.
Problem
Well, at first: I took the code straight from my editor, but somehow it’s not working in the fiddle. I added a comment where the script breaks. Is this a quirk of JSfiddle or did I screw something up?
After clicking on an element with .color, the ID should only appear once in mixed. Instead is appears three times now. so instead of removing it in hilit, it is added again.
Why is it like that & how can I fix that problem? Has this something to do with my use of on()?
Any help is greatly needed & appreciated!
This seems to work now: http://jsfiddle.net/uDsum/2/
EDIT:
Have a look at the documentation of
$.merge()function:http://jsfiddle.net/uDsum/3/