My original idea for today was to have Santa chase the cursor and leave presents everywhere on the screen. When I realized this would not work if the user was not using a mouse, I decided to change the interaction to a click event. Santa would go where the user clicked, but what would make Santa go somewhere? Cookies! I wrote out what needed to happen on a piece of paper first. I find it super useful to use pen and paper when working on problems as I’m more of a visual and kinesthetic learner.
1. event.pageX, click(handler)
To place an image where the user clicked, I had to find out what the coordinates were. This was easily done by using jQuery’s event.pageX and event.pageY, which gives you the mouse position relative to the left side and top of the document. With these coordinates, I could use the the click event handler to append something at the mouse click. First I created a new div wherever the user clicked but then decided I could simply append an image with a different id every time.
Once I had cookies appear wherever the user clicked, my next step was to make the Santa image move to the cookie. I assigned Santa’s positioning to where the cookie was but this resulted in Santa showing up immediately.
I had to break it down to see how much Santa had to move to get to the cookie. This was some simple math by looking at the x and y coordinates. I took the coordinates of the cookie and subtracted Santa’s to get the number of spaces to move. I ran into a road block here for a while and made extensive use of the console.log() function to try to find the problem. I kept getting NaN or undefined and thought it was because I was getting “px” coordinate values from CSS. Turns out it was just because I was calling the function before the variables were declared… (wrong order in the code)… oops!! Once I got the correct number of spaces, I used .animate() to move Santa.
Originally, I set it up so that Santa would move horizontally and vertically (first the x-coordinates and then the y-coordinates). Once the cookies piled up however, this got to be very slow. I changed it so that he would move the shortest distance instead. The shortest distance between two points is a straight line… who remembers proving that in Math class?
When Santa got to the cookie, I wanted the cookie to disappear. I used .hide() to hide the image before reading about .remove() which removes the element completely from the document. Perfect! Cookie eaten.
I added a cookie counter at the end just for fun. Please feed Hungry Santa lots of cookies!
NOTE: I made the initial mistake of using a random number generating function to label my cookies. This meant that numbers could possibly be repeated. What happened was that every now and then, a GHOST COOKIE would appear and disappear by itself! This was super bizarre but fixed when I used a simple incremented variable to label the cookies. This is how I felt while trying to track down the mysterious ghost cookie….