Using .data in jQuery
I am working on a redesign of a cryptogram site. (http://www.dailycryptogram.com). The old version works but has a lot of cumbersome javascript written long before jQuery was available. The handlers for keypress are complex and refreshing the display involves looping over the arrays of the encrypted, unencrypted, used, and available letters. There has to be an easier way.
What have I chosen is to add attributes to the DOM elements where the letters are displayed so the event handlers have all the information necessary without looking it up:
$(".enc_"+el).data("encLetter",el);
$(".enc_"+el).data("solLetter",sl);
$(".enc_"+el).data("dspLetter","");
The event handlers become much simpler:
$(".chosen").live("click",function(){
try{
if($(this).data("dspLetter")!=""){ //we are replacing letter so show original as available
$(".choice."+$(this).data("dspLetter")).show();
}
if($.chosenLetter==""){ //if no letter is chosen make sure textbox is empty
$(".enc_"+$(this).data("encLetter")+">.letterbox").attr("value","");
}
else{ //fill the textbox and remove the letter from the available pool
$(".enc_"+$(this).data("encLetter")+">.letterbox").attr("value",$.chosenLetter);
$("."+$.chosenLetter).hide();
}
$(".enc_"+$(this).data("encLetter")).data("dspLetter",$.chosenLetter);//update data on all occurences of the letter
$.isSolved();
$.chosenLetter="";
$.destinationLetter="";
}catch(except){alert(except)}
});
Also checking for a correct solution is quite easy:
$.isSolved=function(){
var solved=true;
$(".bb>.chosen").each(function(i){ // elements of the bb class holds the data infomation
solved=solved && ($(this).data("solLetter")==$(this).data("dspLetter"));
});
if(solved){
$(".letterbox").addClass("greenboxes").removeClass("letterbox");
}
}
The demo source gives more detais. To solve the cryptogram you can either drag an available letter(red) into the textbox or just type in the textbox. To remove a letter just click on it. You will not be able to enter a letter twice.
Attaching data to a DOM element is quite useful and simple to do. The old way of attaching a primary key to the id of a table row no longer is necessary. Attaching the pk to the data of the row is just as easy and avoids the worry of making sure the id is unique on the page.

There are no comments for this entry.
[Add Comment] [Subscribe to Comments]