Daily Code: Day 1 – Dragon Fire

Daily Code: Day 1 – Dragon Fire

Daily Code: Day 1 – Dragon Fire

Welcome to Day 1 of Daily Code!

Fun with jQuery mouse events

We will keep is simple today with a random project on jQuery mouse events.

This is actually an Easter Egg that I had in place on my company website for a bit, until another developer saw the code and didn’t think it was funny.

First off, lets look at some markup:

The draggable <img/> element needs an id so we can select it. The draggable="false" parameter is used to disable the standard browser functionality of dragging images.

The fire <img/> element is really only there so we can preload the gif. Set to display: none so we cant see it initially.

Next, we make it look good:

Both #dragon and .fire need position: absolute; in order to be placed in the correct spot on the DOM.

#dragon needs a higher z-index than .fire for correct layering.

I tend to use z-index: 9999; to make sure it is the top most element.

Now, for all the magic to happen:

First, we need to set some global variables.

gl is for global event tracking.

w is the window element.

fireShooter is our interval variable for repeative firing.

mouseStillDown is boolean (true/false) to know if we should still be firing.

Next, we define a function for our mouse movement on the window element ( w).

gl = e; updates the global event variable.

#dragon’s CSS positioning is updated with the global client x & y offsets. 'top' : gl.clientY - 90 + w.scrollTop() sets the top value of #dragon to the y position of the mouse minus 90px (due to where the dragon’s head is in the gif) then we add the window scroll top offset so we can scroll the page without the dragon moving. 'left' : gl.clientX - 50 sets the left value of #dragon to the x position of the mouse minus 50px (due to where the dragon’s head is in the gif).

Then, we define the function to make the magic happen.

if( !mouseStillDown ) { return; } checks to see if the mouse is not being pressed.