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.
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.
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/
$('#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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With