When starting out with jQuery you might get frustrated that the animate function doesn’t seem to work. Why doesn’t it seem to work? Well let’s look at this code:
Looks good right? Let’s go over the code just encase you don’t understand it.
- Line 1: When the document is ready run some jQuery Code.
- Line 2 – When an HMTL element with the ID of Box is clicked do these things:
- Line 3 – On this item that has been click let’s animate it with these settings. We could have used “#box” instead of “this” but if we ever had to change from #box to #redBox then we’d have to make two changes. This also makes the jQuery run a tiny bit faster.
- Line 4 – Let’s move the object to the right 500px.
So what’s wrong with this code? It’s a trick question. Before I answer that question let’s first see what the HTML and CSS look like.
After looking at the rest of the code can you now see what’s wrong?
What if I told you that jQuery just doesn’t magically move things across the page. Like everything else in life things don’t just “magically” happen. Coding is no exception. Many moving / animation type methods in jQuery require/use CSS in the background to keep track where things are on the screen. It then updates the screen in such a way that the object seems like it’s moving (kind of like a flipbook).
I hope after that explanation you have a better idea on what is wrong. If you want to move an item normally on a page, you would float an item, position it and then move it X amount pixels to the right, left, up or down.
So the answer to the question about what is wrong is actually “Nothing is wrong with the jQuery code! Our jQuery just relies on belief that the #box is floated and positioned. Once that is done the jQuery can do some “magical” things in the background for you.
We’re going to make one change in the CSS code. We’re going to make the box positioned relative to the flow of the document:
Now if you save the CSS file and refresh the browser and click on the box. You might think that it’s not working again! While it is now moving across the screen it seems to move to the left off the screen! You will check the jQuery code and yes it says:
So why does the box seem move to the left? This might be hard for you to get your head around but you just aren’t reading the CSS spec property properly. How you should read this code is: “From the Right (hand side) move the object 500px! Kind of backward thinking isn’t it? It is to me. So if we change that line to:
the animation will look like you originally thought would happen. The box moves from the left and goes to the right 500px;