Recently I have been working on making a simple snake game and wanted to know what my options were for capturing keyboard events other than simply adding event listeners to the
document, or the
window. Amongst the obvious reasons for avoiding adding event listeners globally, I just want to make a prototype that will create one
canvas element which will capture keyboard events. After doing a quick Google search I found this awesome article saying that it is possible to make any element focusable.
For example make an element as innocuous as a
<div> element focusable by simply defining it’s
Clicking on me will give me the focus!
Clicking on me will do nothing because I have no
The above focusable and non-focusable
<div>‘s are produced by this code:
- Clicking on me will give me the focus!
- Clicking on me will do nothing because I have no
As you can see, only the
<div> with a set
tabIndex is truly focusable. I plan on using this cool hack to make my game’s canvas focusable. I hope you find this neat trick useful as well!
A few days ago I was working on manipulating data that I found in Wikipedia. The data was in a table where the colspans and rowspans were making it difficult to simply programmatically pull data. Then I started looking into code to turn HTML table to JSON but for some reason the rowspans were still causing issues. Finally, I decided to just write a quick and dirty function to get the job done:
The cool thing about this function is that in the case of cells that span multiple columns and/or rows the value in that cell will be written to each corresponding sub-array value.