Loser's Guide Loser's Guide

 Loser's Guide to Life

Sunday, June 21, 2009

A Handy Trick 

I was wondering how you could slide div boxes or expand them. If you look for information about that, you can find all sorts of javascript libraries to download and then lots of stuff that doesn't work so well. Obviously you should be able to do the following with just a few lines of code: Open (or move) a box; close it (or move it back); have one button that does both things; and be able to have as many instances on the page as you like, in other words: re-use the same code. That proved to be the tricky bit. Also you want to do it gradually, because it looks better.

After some experiments I figured out how to do it and, as they say, it's really quite simple:

Of course, this is just a simple example. You could change it around so it grows vertically, or use the same principle to have boxes containing some feature slide onto the page from offscreen, and so on.

function toggleExpand(d2){
if(parseInt(tr.style.width) < 250){expandIt(d2)}
else if(parseInt(tr.style.width) > 80) {unexpandIt(d2)}
function expandIt(com2) {
var slidingDiv = document.getElementById(com2);
var stopPosition = 250;
if (parseInt(slidingDiv.style.width) < stopPosition) {
slidingDiv.style.width = parseInt(slidingDiv.style.width) + 5 + "px";
setTimeout((function(){expandIt(com2);}), 1);
function unexpandIt(com2) {
var slidingDiv = document.getElementById(com2);
var stopPosition = 80;
if (parseInt(slidingDiv.style.width) > stopPosition) {
slidingDiv.style.width = parseInt(slidingDiv.style.width) - 5 + "px";
setTimeout((function(){unexpandIt(com2);}), 1);

This box is 80px wide and expands to 250px. You can, of course, change all that, bearing in mind that the sizes have to be the same in the three parts of the code. You could leave the ids as is, since each box will have its own, and the toggle function is called using that particular id. For example, the div might be <div id="blob" style="...">, and the call will be <a="#" onclick="toggleExpand('blob');return false">. You can also change several things each time. For example, in function expandIt after slidingDiv.style.width...; you can add, on a new line, slidingDiv.style.height...;, or (if you have positioned the box) ...top..., etc., then reverse it in function unexpandIt.



Post a Comment

Watching TV is a good way to tear yourself away from the computer.