0

I have downloaded a HTML5 audio player source from here and I want to change the way the player is controlled from clicking to key pressing.

In js file I found this:

// play click
    $('.play').click(function (e) {
        e.preventDefault();

        playAudio();
    });

and I tried to implement this but didn't work:

document.onkeydown = function(e) {
if (e.keyCode == 78) {
    e.preventDefault();

        playAudio();
    }};

How can I get this to work?

7 Answers 7

3

Try this

document.onkeypress = function(e) {
    if (e.keyCode == 78) {
           e.preventDefault();
           playAudio();
    }
};
Sign up to request clarification or add additional context in comments.

Comments

1

No tested but you can try this

document.body.onkeydown = function(e) {
  //rest of the code
};

Comments

1

change your code to

$('.play').keydown(function (e) {
    e.preventDefault();

    playAudio();
});

this will work

Comments

1

window.addEventListener("keydown", yourFunction, false); //listen to any keydown

function yourFunction(e)
{
 if (e.keyCode == "65") 
 {
   alert("The 'a' key is pressed.");
 }
}

1 Comment

While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
1

Here is the working demo for you:

https://jsfiddle.net/milanchheda/b478atu0/1/

HTML:

 <div class="containerClass">
  <input type="text" class="inputClass" />
</div>

JQuery Code:

 $(".containerClass").on('keydown', '.inputClass', function() {
  alert("keydown...");
});

Comments

1

What you need is .onkeypress.

Assuming that playAudio, you can emulate what the jQuery is doing as follows:

var elements=document.querySelectorAll('.play');
for(var i=0;i<elements.length;i++) elements[i].onkeypress=function(e) {
    if(e.keyCode!=78) return;
    playAudio();
    e.preventDefault();
}

If you’re sure there will only be one such element, you can write:

document.querySelector.onkeypress=function(e) {
    if(e.keyCode!=78) return;
    playAudio();
    e.preventDefault();
}

Comments

0

thank you everybody. i appreciate all your help. my implementation works well after i clear the browser cookies.

Comments

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.