CSS Positioning and setTimeout

May 10, 2010
Episode 24
This week, Nick goes over the basics of CSS positioning and Jim explains setTimeout and a few other nifty JavaScript functions.
Spotlight

Thanks to those who make Doctype possible!

CSS Positioning

The position property in CSS is often misunderstood, but when you’re creating a layout, it’s essential to know how it works. Position allows you break outside of the normal flow of content.

Absolute

By default, the position property is set to “static” on all your page elements. By setting position to absolute, you can take an element out of the normal flow of content and specify its exact location on your page. Using the top, left, bottom, and right properties, you can position the element. For example, if we wanted to move an element to the upper left corner of the page with a bit of spacing from the edge, we could say “left: 100px” and “top: 200px.” This would move the element 100 pixels away from the left edge and 200 pixels from the top of the page.

Fixed

Sometimes when you’re scrolling down a webpage, you’ll notice that some elements appear to be stuck, and stay with you when you scroll down the page. Most of the time, this effect is achieved using fixed positioning.

When you set the position property to fixed, your element will be positioned relative to the viewport, as opposed to absolute where it is relative to the page. In other words, as a user scrolls down the page, the element will stay in the same place. When they resize their browser window, the element will maintain its position relative to the edge of the viewport. After you’ve set an element to use fixed positioning, you just have to specify the top, right, bottom, and/or left properties.

It should be noted that fixed positioning doesn’t usually work on mobile devices, and although there are many hacks to get around this, it’s way beyond the scope of this episode.

Relative

Relative positioning is probably the most misunderstood, but it’s actually pretty simple.

When you set an element’s position to “relative,” and then use top, right, bottom, and left to move the element, you’re actually just telling the browser to move the element from where it would normally be on the page. In other words, the element will be positioned relative to its parent.

You can also use relative positioning to contain an absolutely positioned element. So for example, if you wanted one element to appear in the upper right of its parent element, you would set the parent to relative positioning, and the child element to absolute. Then, you could use the top and right properties to position the element appropriately.

Resources

setTimeout

sometimes in JavaScript, you want to do something, but just not right now. JavaScript’s setTimeout lets you put off for later, what you could do now….

When you have some code that you need to run later, the best way to do it is to use JavaScript’s setTimeout function.

setTimeout is pretty simple, it takes two parameters, the first is the code you would like to run, and the delay before you run the code.

The delay parameter is in milliseconds, so if you wanted your code to run in 2 seconds, you would give the delay parameter the number 2000. Your code won’t necessarily run precisely after that time, because if the JavaScript engine is busy running some other code, it will wait for that piece of code to run to completion before the code in your setTimeout will be executed.

The code parameter can be either a string, or a function.

You can pass it the name of a function, and it will call that function when it is time. You do not put parentheses on the function, because that will call the function right away, instead of giving the function to setTimeout.

function makeAlert(){
  alert("Hello World");
}

setTimeout(makeAlert, 2000);

If you want to pass arguments to your function, you can wrap your full function call with parentheses and arguments inside of an anonymous function. Then later your anonymous function will be called, and since it created a closure around the scope you defined it in, you can safely use any variables you could access when you defined it.

function makeNamedAlert(name){
  alert("Hello " + name);
}

setTimeout(function(){
  makeNamedAlert("Will");
}, 2000);

If you are going to pass setTimeout a method, you will want to again pass the whole expression inside of an anonymous function. If you just pass the method itself, it will lose track of what object it is being called on and the this variable will be wrong.

var john = {
  name: "John",
  sayHello: function(){
    alert('Hello, I am ' + this.name);
  }
}

//Wrong 
setTimeout(john.sayHello, 1000);

//Right
setTimeout(function(){
  john.sayHello();
}, 1000)

The other way is to use a string with a JavaScript expression. This has problems because closures won’t work with the string, so you can’t but any variable names in your string, unless they are globals. It may be a few more characters to construct an anonymous function versus a string, but it will be much more maintainable to use the anonymous function.

setTimeout(“alert("Hello World");”, 1000);

setInterval

If you want to call your code more than once, repeating over a certain interval, setInterval is what you want to use.

Just like setTimeout, setInterval takes two arguments, code, and delay.

setInterval can be useful for constructing animations. Usually simple animations consist of running a piece of code that changes a property a little bit over and over again.

(function(){

  var x = 0;
  document.body.style.position = "relative"

  setInterval(function(){
    document.body.style.left = x + "px"
    x++;
  }, 100)

})()

Most of the times, you want your animation to stop, that’s where clearInterval and clearTimeout come in handy

clear*

When you call setInterval or setTimeout, the return value will be a number. All by itself, this number is pretty meaningless, but it can be used to stop your timeouts or interval.

If you set a timeout, but wanted a way to cancel it before it is called, you can use the clearTimeout function.

When you define your timeout, set it’s return value to a variable. Then if you decide you want to stop it, you can call clearTimeout with that variable.

var timer = setTimeout(myFunction, 2000);

if(cancelTimer){ 
  clearTimeout(timer);
}

Similarly, you can capture the interval number from setInterval, and call clearInterval. This is particularly useful if you are doing an animation, and you have animated all the way through, you can just call clearInterval and you’re done.

var interval = setInterval(myFunction, 2000);

if(cancelTimer){ 
  clearInterval(interval);
}

setTimeout and setInterval both give you really powerful ways to call your javascript later, if they are used correctly, you can create some really cool effects.