0

In my code:

window.addEventListener("keydown",doKeyDown);
function doKeyDown(e)
{
    console.log(e.keyCode);
    var str = String.fromCharCode(e.keyCode);
    console.log(str+":"+e.keyCode);
    var tune = new Audio();
    switch(str)
    {
        case 'Q':
            tune = new Audio("Assets/Tune/C.mp3");
            tune.play();
        break;
    }
}

I want to make the input SHIFT+B so the audio can be played.

I have tried case 'SHIFT+B': but it doesn't work. Is there a way to fix this?

  • 3
    We need more context. What is `str`? This question isn't really answerable as-is. Ideally, your post should include enough code to entirely replicate your problem. – Jeremy Dec 24 '15 at 05:02
  • Do you use **jQuery**? – Abhi Dec 24 '15 at 05:03
  • I've edit the code, basically I want to make an input using SHIFT+B to play the sound. I'm trying to make virtual piano – Kikuja Vonic Dec 24 '15 at 05:18

2 Answers2

1

I'm assuming because you want Shift + B that this is within a keydown event or something? So you should have access to the event like

function onKeyPress(e){
    var evt = e || window.event;
    if(evt.shiftKey) {
        var str = evt.keyCode;
        switch(str)
        {
            //Since we are using the KeyCode, use the ascii value for capital B. 
            case 66:
                tune = new Audio("Assets/Tune/ASharp'.mp3");
                tune.play();
                break;
            default: //Have a default logic
        }
    }
}
Alex Bezek
  • 467
  • 2
  • 7
  • yes, I want to press SHIFT+B so the audio will be played. Thanks for the answer – Kikuja Vonic Dec 24 '15 at 05:20
  • do I need to put window.addEventListener("keyPress",onKeyPress); before function onKeyPress(e) ? – Kikuja Vonic Dec 24 '15 at 05:25
  • yes, you need to attach the function as to an event listener in whichever way you want. http://stackoverflow.com/questions/17255283/the-best-way-to-add-eventlistener-to-an-element – Alex Bezek Dec 24 '15 at 05:28
-1

Try this:-

<input type="text" onkeydown="myFunction(event);">

<script>
function myFunction(event) {
    //keyCode for B = 66
    if(event.keyCode == 66 && event.shiftKey) {
      //Your Code
    }
}
</script>

EXAMPLE FIDDLE

Abhi
  • 4,123
  • 6
  • 45
  • 77