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?

3

2 Answers 2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

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);
}

5 Comments

Using var in if makes me cry. It makes following the scope of variables much more tedious.
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?
Eh @PaulS., my bad. Now I know things. I hate you JavaScript. For those who don't know, see stackoverflow.com/questions/500431/javascript-variable-scope
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.
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.