Home > DeveloperSection > Forums > Show image when key is pressed with jQuery
lois waisbrooker
lois waisbrooker

Total Post:70

Points:494
Posted on    April-08-2013 2:40 AM

 JavaScript JavaScript 
Ratings:


 2 Reply(s)
 935  View(s)
Rate this:
Hi Mindstickians!

I'm trying to make a simple app that when a key is pressed on the users keyboard an image appears respective to that letter. I would like to do this for the entire alphabet (a, b, c...)

if a is pressed a.jpg shows up on my page, if r was pressed r.jpg would appear and so on.

I was going to do this with a mega list of if else statements only im sure there must be another way?

var ctrlPressed = false;
$(window).keydown(function(evt) {
  if (evt.which == 17) { // ctrl
    ctrlPressed = true;
      alert('sdf');
  }
})

Thanks in advance!


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    April-08-2013 7:42 AM

Hi Lois!

var letters = "abcdefghijklmnopqrstuvwxyz";
letters = letters.split("");

$(window).keydown(function(e){
    key = e.which - 65; //makes a-z = 1-27
    key = letters[key];
    $('img[src="' + key + '.jpg"]').show();
}

Vijay Shukla

Total Post:100

Points:700
Posted on    April-08-2013 8:05 AM

Hi Lois!

Match again a-z as below

$(window).keydown(function(e) {
    var key = String.fromCharCode(e.which).toLowerCase();
    if(/[a-z]/i.test(key) {
        alert(key+'.jpg');
    }
});

Don't want to miss updates? Please click the below button!

Follow MindStick