1

This is a sample javascript code to alert the user if he clicks shift + 1 (or 2,3...9)

But as you see this code is almost the same.

a = window.event.keyCode;

var b = window.event.shiftKey

if (a == 49 && b) {
    alert(document.getElementById('alert1').length)
}
if (a == 50 && b) {
    alert(document.getElementById('alert2').length)
}
if (a == 51 && b) {
    alert(document.getElementById('alert3').length)
}
if (a == 52 && b) {
    alert(document.getElementById('alert4').length)
}
if (a == 53 && b) {
    alert(document.getElementById('alert5').length)
}
if (a == 54 && b) {
    alert(document.getElementById('alert6').length)
}
if (a == 55 && b) {
    alert(document.getElementById('alert7').length)
}
if (a == 56 && b) {
    alert(document.getElementById('alert8').length)
}
if (a == 57 && b) {
    alert(document.getElementById('alert9').length)
}

Is there any javascript (it can be jQuery) code (using for(){} method or something else) that will do the same job by writing less code and the other code to be generated by the browser and executed when is required?

David G
  • 94,763
  • 41
  • 167
  • 253
Idrizi.A
  • 9,819
  • 11
  • 47
  • 88

2 Answers2

9

You should not create executable Javascript but review your code.

Repetitive code can most times be written as a loop or in your case by math.

if(a < 58 && a > 48 && b) {
  alert(document.getElementById('alert'+(a-48)).length)
}
AmShaegar
  • 1,491
  • 9
  • 18
2

You probably don't really want code generation + execution, that can get pretty dangerous.

All you need is a little DRYing of your code:

var ALERT_KEYCODE_OFFSET = 48;
var alertIndex, alertId;
if (a >= 49 && a <= 57 && b)
{
    alertIndex = a - ALERT_KEYCODE_OFFSET;
    alertId = 'alert' + alertIndex;
    alert(document.getElementById(alertId).length);
}
schematic
  • 1,964
  • 1
  • 16
  • 20
  • 2
    Using `var` in `if` makes me cry. It makes following the scope of variables much more tedious. – Paul S. Dec 30 '12 at 18:07
  • So it's less tedious if everything's just global? OK. Is there a special scoping rule for "if" that I'm not aware of? – schematic Dec 30 '12 at 18:13
  • 2
    Eh @PaulS., my bad. Now I know things. I hate you JavaScript. For those who don't know, see http://stackoverflow.com/questions/500431/javascript-variable-scope – schematic Dec 30 '12 at 18:19
  • I mean it's less tedious if you set the `var` before the `if`, not inside it. `if` blocks don't have their own scope unless you can use JavaScript 1.7's `let`, any `var` gets hoisted upwards to the beginning of the scope. This means if you're trying to find if/which scope a `var` is declared, it can get confusing if written like this. EDIT Yup, non-block-scoping is one of the many quirks of JavaScript. – Paul S. Dec 30 '12 at 18:20
  • Yeah, I had this foolish idea that there was such a thing as block scope for `var` (without using `let`). I mean, it _looks_ like it should. Thanks for showing me otherwise! – schematic Dec 30 '12 at 18:24