HTML Hack – Making Any Element Focusable

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 body, 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 tabIndex attribute:

  • Clicking on me will give me the focus!
  • Clicking on me will do nothing because I have no tabIndex.

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 tabIndex.

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! 😎

JavaScript – Global Eval Using Data URIs

WARNING:
This post is intended solely to educate and is not to by any means encourage that anyone use this method to globally evaluate JavaScript code. Most JavaScripters avoid eval(), especially globalEval() (like what is provided in libraries such as jQuery), as if it were the plague. Its use can be substantiated in some cases but it is of the utmost importance to consider the risks involved with the two functions.
SCRIPTER’S DISCRETION IS ADVISED. 😆

Since many modern browsers now offer the ability to use Data URIs for more than just images, we could actually use them to essentially run a string of JS code on a page in the global namespace. How so? Here is the code for a simple globalEval() function that can be used in modern browsers such as Chrome and FireFox:

Conceivable Uses

As the jQuery docs mention, one good reason that this type of function exists is to provide a way to execute external scripts in the global namespace. It is important to reiterate that you must use this type of function sparingly, analyzing the reasons why you are using it in the first place.

Another conceivable use would be if you are developing a browser extension that really needs to execute a JavaScript snippet on certain pages. At this point though, if you decide that you want to publish your extension through Google or whichever other channel, that authority may deny your request in the interest to safeguard users from malicious intent. On the other hand, if you are simply creating something like a Chrome extension for private use, I believe you should be able to use this type of approach to execute additional code within pages visited by the user.

Final Words

Much more could be said of the uses of globalEval() and reasons not to use globalEval(), but I like to keep my posts short. If you do find yourself thinking you want to use globalEval(), be sure to calculate the risks (such as possibly running malicious code if it is coming from an external source). Also, this implementation, although very simple, will not work in older browsers such as IE7 (and hasn’t been tested in IE8 or IE9). If you really need a version that has been tested for almost all browsers, I suggest using jQuery’s implementation or perhaps this one. Be careful! 😎

JavaScript – Creating A Downloadable File in the Browser

Let’s say that you have an array of arrays that is dynamically generated and you would like to provide a download link/button to download it as a CSV. How would you go about doing it? Ordinarily you would go about sending the data to the server which would then be able to make a downloadable version of the data. Believe it or not, there is also a way to do it in modern browsers without ever needing to make additional requests to a server. The following JSBin proves this by providing a large textarea that can be modified and a download link which when clicked (in modern browsers) will download a file with the specified contents:
JS Bin

How does it work? We basically just rely on data URIs. For instance, clicking here should result in downloading a file with text saying Hello World!!!. This an simply an anchor element (<a>) with an href of data:text/plain;charset=utf-8,Hello%20world!!!. In addition, some newer browsers (Chrome and FireFox) support the download attribute being set to specify the default file name when downloaded.

How do you get it to be dynamic? You can simply modify the href attribute when the link is clicked, by binding the necessary code to the click event of the link. Here is a simple version of the JSBin shown:

<!DOCTYPE html>
<html>
  <head>
    <style type="text/css">...</style>
    <script type="text/JavaScript">
    window.onload = function() {
      var txt = document.getElementById('txt');
      txt.value = window.onload + '';
      document.getElementById('link').onclick = function(code) {
        this.href = 'data:text/plain;charset=utf-8,'
          + encodeURIComponent(txt.value);
      };
    };

    main();
    </script>
  </head>
  <body>
    <div id="txtWrap">
      <textarea id="txt"></textarea>
    </div>
    <a href="" id="link" download="code.txt">Download Above Code</a>
  </body>
</html>

Ignoring the omitted CSS rules, you will notice that the concept is quite simple. The one thing you want to remember is that in order to make sure that all characters are downloaded correctly you will want to use encodeURIComponent(). I have seen implementations that use escape(), but that function is deprecated and doesn’t always encode the characters correctly.

Have fun making your quick custom download buttons 😎