Question

Why this code don't work properly?

<img src="picture.jpg" id="picture"/>

<script>
document.getElementById('picture').onkeydown = function() {alert('tekst');}
</script>
Was it helpful?

Solution

Your image doesn't have focus so it won't listen to the 'onkeydown' event. I'm not sure if it is possible to give an image focus in order for your onkeydown event to work.

Instead you could place your image within an a-tag which can have focus and therefore can listen to the onkeydown event.

Something like this:

<a id="picture" href="#">
    <img src="picture.jpg" />
</a>

<script>
   // The a tag
   var picture = document.getElementById('picture');
   // You have to put focus on the atag (or any element that you want to have for you onkeydown event.
   picture.focus();
   // Now your event will work
   picture.onkeydown = function() {
       alert('tekst');
   }
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top