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

Total Post:70

Posted on    April-08-2013 2:40 AM

 JavaScript JavaScript 

 2 Reply(s)
 1143  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;

Thanks in advance!


Total Post:604

Posted on    April-08-2013 7:42 AM

Hi Lois!

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

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

Vijay Shukla

Total Post:100

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) {

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

Follow MindStick