Changing inline styles
Viewers: in countries Watching now:
- Creating variables, functions, and loops
- Writing conditional code
- Sending messages to the console
- Working with different variable types and objects
- Creating and changing DOM objects
- Event handling
- Working with timers
- Building smarter forms
- Using regular expressions
Changing inline styles
Down at the bottom, I have a window.onload that's going to call a setTimeout function that passes in beginAnimate, 5000. That simply means do a single call to the beginAnimate function in five seconds after the page is loaded. What does that do? Well, up here in beginAnimate what I'm doing is I've got three lines that all grab that actual div, which currently is part of the body of the page. What I'm going to do is a couple of CSS style tricks.
I'm going to set its position to absolute, then its left position to 0 pixels, and its top position to 100 pixels from the top. Well, then what? I'm now going to call setInterval, and this is the repeating timer event that's going to call the animateBox function about 20 times a second. And if you remember, setInterval gives you back a variable, it gives you back a handle to that interval, which I'm just going to store in intervalHandle, which is defined as a global variable up here.
So, really all the work is happening in this function called animateBox. First thing it does is say, whatever the current position is I'm going to add 5 to it. In fact, the first time this ever gets called current position will be 0. So we add 5 to it. I then grab that div and set its style.left property to whatever the current position is, and then I'm going to use the plus sign and add px, remembering that we have to pass in any units that are used by that CSS style--in this case, pixels.
Now, currentPos is actually a number, but px is a string, so it will concatenate these together as a string. So it will be 5 px, 10 px, 200 px, and so on. And all that I'm doing here is saying, if the current position, the leftmost position, gets to be greater than 900-- and bear in mind what I'm checking here is just the number variable without the px, that's fine-- I'm going to clear the interval, and it makes it so that this function doesn't get called anymore, and then I'm going to reset the div to its original styles.