Codecademy Jquery Events
by pixeloco
HTML
<h1>Fade</h1>
<div id="fader1"></div>
<div id="fader2"></div>
<h1>Double Click</h1>
<div id="double"></div>
<h1>Hover Changes</h1>
<div id="hover1"></div>
<h1>Focus</h1>
<form>Name: <input type='text' name='name'></input></form>
<h1>Keydown/Animate</h1>
<div id="key"></div>
<h1>Cases</h1>
<img src="http://i1061.photobucket.com/albums/t480/ericqweinstein/mario.jpg"/>
CSS
h1 {font-size:14px; margin:20px 0 5px 0;}
#fader1, #fader2 {background-color:blue; width:200px; height:50px;}
.red {background-color: red !important; /*needed to overwrite the bg set in id*/}
#double {background-color:orange; width:100px; height:50px;}
#hover1 {background-color:pink; width:100px; height:50px;}
.hover2 {background-color:red !important;}
#key {background-color:purple; width:50px; height:50px; position:relative;}
img {position:relative; top:0; left:0}
JavaScript
$('#fader1').fadeOut('fast');
$('#fader2').click(function(){
$(this).fadeOut('slow');
});
$('#fader2').hover(function(){
$(this).addClass('red');
});
$('#double').dblclick(function(){
$(this).fadeOut('slow');
});
$('#hover1').hover(
function(){
$(this).addClass('hover2');
},
function(){
$(this).removeClass('hover2');
});
//why is this different/better than just using toggleClass? makes more sense using something different on the mouseout, like css('width', '200px')
$('input').focus(function(){
$(this).css('outline-color', 'red');
});
$(document).keydown(function(){
$('#key').animate({left:'+=10px'},500);
});
$(document).keydown(function(key) {
switch(parseInt(key.which,10)) {
// Left arrow key pressed
case 37:
$('img').animate({left: "-=10px"}, 'fast');
break;
// Up Arrow Pressed
case 38:
$('img').animate({top: "-=10px"}, 'fast');
break;
// Right Arrow Pressed
case 39:
$('img').animate({left: "+=10px"}, 'fast');
break;
// Down Arrow Pressed
case 40:
$('img').animate({top: "+=10px"}, 'fast');
break;
}
});
//only works with top/left so define movement accordingly