Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load javascript and CSS files based on a sequence of keypresses

I want to load these two files

<link rel="stylesheet" type="text/css" href="sewmuchcss.css">
<script type="text/javascript" src="sewmuchjs.js"></script>        

in my header only when a user presses "up, up down, down, left, right, left, right." How would I go about accomplishing this? Would I use jquery, or javascript. What would I have to do? Thanks in advance for any help or answers.

like image 255
thedullmistro Avatar asked Oct 12 '12 06:10

thedullmistro


People also ask

How to load CSS dynamically in JavaScript?

Load CSS and JS files dynamically: We create a script element for the JS file and link element for the CSS file as required using DOM, assign the appropriate attributes to them, and then add the element to the desired location within the document tree using the element. append() method.


2 Answers

I would use jQuery, and you can use the following algorithm to check for the multiple keys in a row:

var keysPressed = [];
                       //  U,  U,  D,  D,  L,  R,  L,  R
var MAGIC_KEY_SEQUENCE = [ 38, 38, 40, 40, 37, 39, 37, 39 ]

$('body').on('keydown',function(e){
     var code = (e.keyCode ? e.keyCode : e.which);

     keysPressed.push( code );

     if ( keysPressed[ keysPressed.length - 1 ] == MAGIC_KEY_SEQUENCE[ keysPressed.length - 1 ] )
     {
       // so far so good

       if ( keysPressed.length == MAGIC_KEY_SEQUENCE.length )
       {
         // all keys were pressed in the right order!
         alert( 'hurray!' );

         $('<link/>').attr({
             rel:'stylesheet',
             type:'text/css',
             href:'sewmuchcss.css'}).appendTo('head');
         $.getScript('sewmuchjs.js');
       }
     }
     else
     {
       // something didn't match, so reset the list
       keysPressed = []       
     }
})​

Play with it here: http://jsfiddle.net/japanick/vfRqk/

like image 155
Nick B Avatar answered Oct 03 '22 01:10

Nick B


$('#target').keypress(function(){
     var code = (e.keyCode ? e.keyCode : e.which);
     if(code == 21) // write your preferable keycodes here
     {
          $('<link/>').attr({ rel: 'stylesheet', type: 'text/css' href:'sewmuchcss.css' }).appendTo('head');
          $.getScript('sewmuchjs.js');
     }
})

fiddle: http://jsfiddle.net/pwunq/

like image 31
karaxuna Avatar answered Oct 03 '22 01:10

karaxuna