SHOW IMAGE WHEN KEY IS PRESSED WITH JQUERY

lois waisbrooker

Total Post:70

Points:494
Posted by  lois waisbrooker
 1190  View(s)
Ratings:
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!
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: Show image when key is pressed with jQuery

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

  1. Vijay Shukla

    Post:100

    Points:700
    Re: Show image when key is pressed with jQuery

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!