PDA

View Full Version : Resolved Help with Compacting Codes [jQuery]



fr600
06-22-2011, 12:14 AM
I'm not an expert and so my codes are huge making the file size large. There are shorter ways to do it and I don't know how and I'd really appreciate if you could help me with this.

Here's the first one, I'm providing only 6 lines but there are more:


$("#image1").click(function(){shiftH();doThis(1);});$(document).bind('keydown','1',function(){shiftH();doThis(1);});
$("#image2").click(function(){shiftH();doThis(2);});$(document).bind('keydown','2',function(){shiftH();doThis(2);});
$("#image3").click(function(){shiftH();doThis(3);});$(document).bind('keydown','3',function(){shiftH();doThis(3);});
$("#image4").click(function(){shiftH();doThis(4);});$(document).bind('keydown','4',function(){shiftH();doThis(4);});
$("#image5").click(function(){shiftH();doThis(5);});$(document).bind('keydown','5',function(){shiftH();doThis(5);});
$("#image6").click(function(){shiftH();doThis(6);});$(document).bind('keydown','6',function(){shiftH();doThis(6);});

And here's the other one from the functions shiftH an doThis:


if(n=='1'){rr='A';}
else if(n=='2'){rr='B';}
else if(n=='3'){rr='C';}
else if(n=='4'){rr='D';}
else if(n=='5'){rr='E';}
else if(n=='6'){rr='F';}

Thanks

Nile
06-22-2011, 12:55 AM
As for the first, you can change that to:


for(var i = 1; i <= 5; ++i){
$("#image" + i).click(function(){
shiftH();
doThis(i);
});
$(document).bind('keydown', '' + i + '', function(){
$("#image" + i).click();
});
}

For the second, I guess you have two options.

I would use:


switch(n){
case '1':
rr = 'A';
break;
case '2':
rr = 'B';
break;
case '3':
rr = 'C';
break;
case '4':
rr = 'D';
break;
case '5':
rr = 'E';
break;
case '6':
rr = 'F';
break;
}


But a second, less preferred option would be:


var conditions = [['1', 'A'], ['2', 'B'], ['3', 'C'], ['4', 'D'], ['5', 'E'], ['6', 'F']];
for(var x in conditions){
if(n == conditions[x][0]){
rr = conditions[x][1];
}
}

fr600
06-22-2011, 07:30 AM
The first one didn't work, it returns 6 whenever I click 1~5. But this one did:


function mkclosure(i){
return function(){ shiftH(); doThis(i); }
}

for (var i=1; i<=6; i++){
var f=mkclosure(i);
$('#image'+i).click(f);
$(document).bind('keydown', ''+i, f);
}

The second and third one works well.

Thank you so much. :)

Nile
06-23-2011, 01:22 AM
No problem, I'm glad to help :D

Here on DD, we like to keep things organized. In an effort to do so, you have the option to set a thread to resolved when an issue is fixed. To make the status of the thread resolved:
1. Go to your first post
2. Edit your first post
3. Click "Go Advanced"
4. In the dropdown next to the title, select "RESOLVED"