As I delve into the world of jQuery, I've decided to create a simple Super Mario imitation. The concept is to control Mario using arrow keys and fade out mushrooms once Mario reaches them. However, my attempts at achieving this result have not been successful. If anyone could provide guidance in the right direction, I would greatly appreciate it!
Below is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Super Mario!</title>
<link rel='stylesheet' type='text/css' href='stylesheet.css'/>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<img class="mushroom" src="http://ih2.redbubble.net/image.6378228.5104/sticker,375x360.u2.png"/>
<img class="mario" src="http://i1061.photobucket.com/albums/t480/ericqweinstein/mario.jpg"/>
</body>
</html>
Here is the CSS code:
img {
position: relative;
left: 0;
top: 0;
}
.mushroom {
position: relative;
left: 300;
top: 200;
width: 48px;
height: 48px;
}
And here's the jQuery implementation:
$(document).ready(function() {
// Keydown function to move mario
$(document).keydown(function(key) {
switch(parseInt(key.which,10)) {
case 37:
$('.mario').animate({left: "-=10px"}, 'fast');
break;
case 38:
$('.mario').animate({top: "-=10px"}, 'fast');
break;
case 39:
$('.mario').animate({left: "+=10px"}, 'fast');
break;
case 40:
$('.mario').animate({top: "+=10px"}, 'fast');
break;
}
$(document).on('keydown', '.mario', function(e){
var x = e.clientX - this.offsetLeft,
y = e.clientY - this.offsetTop;
if (x > 300 && x < 400 && y > 200 && y < 300) {
$('.mushroom').fadeOut('slow');
}
});
});
});
I initially attempted to use an IF statement to check Mario's position using CSS, but that approach didn't work as expected. It seems that the CSS is not updated on key press events. Therefore, I'm currently stuck on this issue.
The original IF statement idea looked like this:
// On Mario's arrival remove Mashroom
$(document).on('keydown', '.mushroom', function() {
if($('.mario').css("left")=="300" && ("top")=="200") {
$('.mashroom').animate({left: "+=10px"}, 'fast');
}
});
Thank you in advance for any assistance provided!