- 06
- Mar
Well, my last tutorial post about creating a collapsible div (no animation) was a huge hit, receiving over 1100 diggs.
I actually learned quite a bit from the comments. First of all, I implemented the wp-cache 2.0 so my server doesn’t go down after 70-100 diggs again, haha. Secondly, I found people wanted animation… Digg comment style sliding. I can do that.
So, expanding on the last tutorial, I’ve coded a small Javascript library that will allow that functionality. It’s not meant to be a mootools or a script.aculo.us replacement… those are far more advanced libraries. This is just a simple, quick bit of code you can apply to your websites to improve the user experience a bit.
In this tutorial, we will create functions to slide DIVs up and down. It supports multiple animations happening simultaneously, as well as a variable animation length. It’s also time-based, rather than increment based, so it’ll animate the same speed on most computers; old computers won’t take 10 minutes for a DIV to slide down.
Click here to see the final product.
First, create a new file on your webserver called motionpack.js - this is where we will store all the javascript functions for the animations, rather than cluttering up the top of the webpage itself, and slowing down it’s load time. In the beginning of that file, let’s first declare some initial variables:
var timerlen = 5; These are the variables you will change if you want to tweak the speed of the animation on your site. timerlen is how often the Javascript function will run to alter the DIV’s properties (altering height or opacity)… it’s probably best to leave this at 5. Any lower will be slightly smoother, but will require your visitors have a better computer (otherwise it’ll be choppy), and much higher will be choppy on everyone, because it’s not updating enough to look smooth. The next variable, slideAniLen, is how long it should take a DIV to completely slide up or completely slide down. This is in milliseconds, so setting it to 500 means it’ll take half a second to complete the animation effect. This is fairly quick, so some people might want to increase and make it a bit slower.
var slideAniLen = 500;
Now, the next part of the JS file:
var timerID = new Array(); These are some variables we’ll use throughout the code below to keep track of our animations. We use arrays for each object to allow multiple animations to happen simultaneously. We’ll explain where each of these are used later on, but for now, simply paste them into your JS file.
var startTime = new Array();
var obj = new Array();
var endHeight = new Array();
var moving = new Array();
var dir = new Array();
Now we’re getting to the actual functions. These first functions are what we call from our website itself. They essentially serve as the API for this mini-library.
function slidedown(objname){ This code adds the functions to call when requesting a DIV start sliding up or down. Let’s first look at the slideup() function. We pass it a single parameter- the DIV’s id (objname). The first line checks if the moving variable is set to true for that DIV, so we don’t begin animation on one that’s already moving. Once an animation starts, it will finish uninterrupted. If it is moving, on line 3, we return (exit from the function) so no further animation begins. The next line is a sanity checking if-statement. This function is beginning the slide down process of a DIV, and if a DIV’s display attribute is not set to none (not visible), we assume it’s already slid down and visible, so we can exit the function (abort the process), since there’s nothing else for us to do here. If those checks complete without any complications, we’re now ready to begin the sliding process, so we set the moving variable to true (so no other animation can start until we’re done), we set the direction variable to down (so it knows which way to move), and we call the function startslide(), which we’ll get to in a moment. The slideup() function is very similar, except it checks on the 3rd line inside that function to ensure the display property is not set to “none”, so the DIV is not visible, otherwise we have nothing to slide up, and we can abort the start slide process.
if(moving[objname])
return;
if(document.getElementById(objname).style.display != "none")
return; // cannot slide down something that is already visible
moving[objname] = true;
dir[objname] = "down";
startslide(objname);
}
function slideup(objname){
if(moving[objname])
return;
if(document.getElementById(objname).style.display == "none")
return; // cannot slide up something that is already hidden
moving[objname] = true;
dir[objname] = "up";
startslide(objname);
}
Now, I hope you guys are hanging in there, we’re almost through the tricky parts.
The next function we’ll throw in the file is the startslide() function mentioned above:
function startslide(objname){ Okay, the last two functions were for making sure we really want to start the slide, and doing all the initial preparations. This function, startslide(), is where we actually begin the sliding process. We, as always, pass the DIV’s id (objname) that we’re working with as the function’s parameter. On the first line of this function, we set it in the obj[] array, so we can keep track of the id throughout the animation process. The next two lines set the endHeight to the original height (so we know where to start sliding from, or how far down to slide to), and the startTime, so we can keep track of how long this animation has been going on. Following this we have a nice three line if-statement that checks if we’re sliding down, and if we are, resizes the DIV’s height to 1px… a starting point to slide down from. Next it sets the object’s display attribute to “block”, making it visible (redundant if sliding up, but a good just-in-case measure never-the-less). Note: You might want to use “inline” instead of “block”, depending on your circumstances (inline will allow the DIV to have other content to the left and right of it, rather than adding a line break before and after it like block does), just be aware to change the other occurrences of “block” to “inline” if you do this. Finally the last line of the function is where we’ve set the initial timer, which will call the sliding function ever few milliseconds (depending on your settings of timerlen up top), and actually perform the animation itself.
obj[objname] = document.getElementById(objname);
endHeight[objname] = parseInt(obj[objname].style.height);
startTime[objname] = (new Date()).getTime();
if(dir[objname] == "down"){
obj[objname].style.height = "1px";
}
obj[objname].style.display = "block";
timerID[objname] = setInterval('slidetick('' + objname + '');',timerlen);
}
Now, the function the above timer called was slidetick(), which is the next part of our motionpack.js file.
function slidetick(objname){ This function is what actually does the animation itself. The first line checks how long the animation has been in progress, by subtracting the animation’s start time from the current time. There’s then an if-statement that checks if the animation has exceeded the preset time (at the top of this file) for an animation’s length, and if so, it calls the endSlide() function, which cleans up (discussed below). If the elapsed time is not greater than the max time (the else-statement), it calculates the variable “d”. This calculation takes the ratio of time that’s progressed so far in the animation, and multiplies it by the final height of the DIV, so if half the time has progressed, for example, the variable d will contain half the height. Then it checks the direction, and if we’re sliding up, it alters d to it’s inflection… sliding the opposite direction (three quarters the way through the time would either be three quarters the way down if sliding down, or a quarter of the way from the top, if sliding up). Next we set the DIV’s height to “d” using it’s CSS style.height property.
var elapsed = (new Date()).getTime() - startTime[objname];
if (elapsed > slideAniLen)
endSlide(objname)
else {
var d =Math.round(elapsed / slideAniLen * endHeight[objname]);
if(dir[objname] == "up")
d = endHeight[objname] - d;
obj[objname].style.height = d + "px";
}
return;
}
Now, the last function we’re needing in the motionpack.js file is the endSlide() function:
function endSlide(objname){ This is the function that’s called when the time runs out on an animation. It finishes everything and cleans up. The first line kills the animation timer, so it doesn’t keep trying to slide. The if-statement checks, and if it was sliding up, it hides the DIV by changing it’s display attribute to “none”. It readjusts the DIV’s height to the original height, so future animations will work fine on it. Then finally there are all those delete lines, deleting any array element we created to keep track of the different animations throughout the process. This cleans up a bit to ensure there are no memory leaks (for sites with lots of animations), etc. After this function is completed, the animation process is done.
clearInterval(timerID[objname]);
if(dir[objname] == "up")
obj[objname].style.display = "none";
obj[objname].style.height = endHeight[objname] + "px";
delete(moving[objname]);
delete(timerID[objname]);
delete(startTime[objname]);
delete(endHeight[objname]);
delete(obj[objname]);
delete(dir[objname]);
return;
}
Now you can save that file, with all the pieces above saved up, and upload it to your webserver.
To download the entire above JS file, you can get it here.
Now, we have our entire mini-library done…. so how do we use it?
First we need to include it in our website. This is done by adding this quick line to your website on every page that you’re using the animation, preferably in the HEAD tag:
<script language="JavaScript" src="motionpack.js"></script> This code assumes the file you uploaded is named “motionpack.js” and is in the same folder as your website source code itself. Another common practice is to create a folder called js/ and put all your javascript include files there together, and in that case, you’d change the src tag above line to “js/motionpack.js”. Easy.
Now that page of your website has sliding abilities! But how do we use them?
First, let’s create a DIV, like we did with our last collapsible DIV tutorial:
<div id="mydiv" style="display:none; overflow:hidden; height:95px;"><h3>This is a test!<br>Can you see me?</h3></div> Notice we did make one change though. We added an “overflow: hidden” attribute and “height:95px” to the style property of the DIV. These property MUST be present on all DIVs you use for sliding. If you don’t include the overflow attribute, it’ll look very ugly, with text overlapping on other content and such. If you don’t include a static height here, it won’t know how far to slide, so it won’t work at all. Aside from that, it’s virtually the same. You can put whatever you want inside the div, just be sure to adjust the height accordingly.
The difference is this time our link calls functions from our library above. Here’s an example of what a Slide Down link might look like:
<a href="javascript:;" onmousedown="slidedown('mydiv');">Slide Down</a> Notice in the onmousedown function we call the slidedown() function from our above library. This will begin the animation and slide the DIV down, until it’s completely visible. You can replace slidedown() with slideup() to do just that, slide the DIV up.
As a challenge to you, try using what you’ve learned in this tutorial and the last to create a toggleSlide() function. It would be a simple if-statement to check if the link’s “display” property, and either slide it up or down, depending on it’s state. We did something very similar in the last tutorial, so try applying that here!
And finally, he’s a working example of it:
Hope this helps!
Edit: Due to a high number of requests, I’ve made a followup post explaining how to use this code in a one-click toggle situation: Toggle Sliding DIV ![]()

March 6th, 2007 at 6:01 am
Thats some nice work.
March 6th, 2007 at 7:08 am
Cool work
March 6th, 2007 at 8:46 am
I can’t get your examples (Slide Up, Slide Down links) to work with FireFox, but it works with IE. Do you know why? Great Tutorial Though..
March 6th, 2007 at 8:53 am
Nice one, it will be nice to wipe “mydiv” horizontal too
March 6th, 2007 at 9:05 am
Scott, what problem are you having in Firefox? I’m using Firefox 2.0 right now and the sliding seems to work fine.
Regards,
- Harry
March 6th, 2007 at 9:07 am
[…] Note, I’ve since made an updated post to this, with Digg comment style sliding animation included. Digg Article - Actual Link […]
March 6th, 2007 at 9:58 am
[…] opciones adicionales tras enlaces que al ser pulsados muestran su contenido. En la página de Harry Maugans nos encontramos con un script que nos permitirá realizar este efecto haciendo visible el contenido […]
March 6th, 2007 at 9:59 am
great job
March 6th, 2007 at 2:30 pm
How does display:none effect search engine optimization? Do search engines ignore content that is within a display:none div?
March 6th, 2007 at 3:25 pm
awesome
March 6th, 2007 at 3:25 pm
Really cool.
March 6th, 2007 at 3:25 pm
You might want to use unique IDs, from your front page your earlier example of a hidden div activates and deactivates the div in this example.
March 6th, 2007 at 3:25 pm
Thanks for sharing, I’ve been wanting to do something like this!
March 6th, 2007 at 3:27 pm
Sweet. Thanks for the tip. I commented yesterday, but will definatly be adding this as well.
March 6th, 2007 at 3:28 pm
Real nice that - well explained tutorial.
March 6th, 2007 at 3:30 pm
This is pretty neat. Thanks for taking the time to write it up!
March 6th, 2007 at 3:31 pm
Nice work, thanks for the share
March 6th, 2007 at 3:31 pm
im not using firefox 1.5 and its not working. but, like the other guy, it works in IE.
March 6th, 2007 at 3:32 pm
[…] 6, 2007 at 7:32 pm · Filed under Uncategorized How to Create Digg Comment Style Sliding DIVs with Javascript and CSS A great step-by-step tutorial on how to create a sliding DIV like Digg uses for burying comments. […]
March 7th, 2007 at 2:43 am
Awesome!
March 7th, 2007 at 8:42 am
[…] read more […]
March 7th, 2007 at 10:09 am
Have you done browser compatibility checks?
Which browsers will this not work with, and does the information default to visible?
March 7th, 2007 at 10:27 am
Wow this is so cool!
March 7th, 2007 at 11:52 am
Works fine for me in Firefox 2.0.0.2
March 7th, 2007 at 12:50 pm
i am liking the comment system.
March 7th, 2007 at 12:57 pm
It is cool
March 7th, 2007 at 2:09 pm
[…] ich mich den ganzen Tag mit Ajax rumgeärgert habe, poste ich jetz zum Ausgleich ein Tutorial von Harry Maugans über, dank Ajax-scripts, animierte sich auf- und zu-klappende […]
March 7th, 2007 at 2:20 pm
[…] Harry Maugans » How to Create an Animated, Sliding, Collapsible DIV with Javascript and CSS I’ve coded a small Javascript library that will allow that functionality. It’s not meant to be a mootools or a script.aculo.us replacement… those are far more advanced libraries. (tags: css javascript webdesign div tutorial animation ui) […]
March 7th, 2007 at 2:36 pm
Awesome! First js script tutorial I could understand! Thanks again for sharing.
March 7th, 2007 at 5:13 pm
Awesome!
March 7th, 2007 at 6:09 pm
Thanks.. That is very cool.
March 7th, 2007 at 8:21 pm
[…] Harry Maugans » How to Create an Animated, Sliding, Collapsible DIV with Javascript and CSS (tags: ajax) […]
March 7th, 2007 at 11:56 pm
Cool.
Is there any way to use a dynamic height?
March 8th, 2007 at 6:54 am
I like the animation pattern, simple and effective. Could use some cross-browser comliancy, but the just of it is conveyed nicely.
March 8th, 2007 at 6:55 am
I like the animation pattern, simple and effective. Could use some cross-browser compliancy, but the just of it is conveyed nicely.
March 8th, 2007 at 2:54 pm
I am getting objname is undefined error in the error console. Anyone else running into a problem.
March 8th, 2007 at 4:14 pm
Fixed the error I had to add an extra escape character to line 257
out.print.ln(”timerID[objname] = setInterval(’slidetick(” + objname + ”);’,timerlen);”)
needed to be
out.println(” timerID[objname] = setInterval(’slidetick(” + objname + ”);’,timerlen);”);
March 9th, 2007 at 6:06 am
Great work it saved me a lot of headaches, Thanks!
I have added a fade effect to it , it fades AND slides in and out now: The new code is below
var timerlen = 5;
var slideAniLen = 250;
var timerID = new Array();
var startTime = new Array();
var obj = new Array();
var endHeight = new Array();
var moving = new Array();
var dir = new Array();
function slidedown(objname){
if(moving[objname])
return;
if(document.getElementById(objname).style.display != “none”)
return; // cannot slide down something that is already visible
moving[objname] = true;
dir[objname] = “down”;
startslide(objname);
}
function slideup(objname){
if(moving[objname])
return;
if(document.getElementById(objname).style.display == “none”)
return; // cannot slide up something that is already hidden
moving[objname] = true;
dir[objname] = “up”;
startslide(objname);
}
function startslide(objname){
obj[objname] = document.getElementById(objname);
endHeight[objname] = parseInt(obj[objname].style.height);
startTime[objname] = (new Date()).getTime();
if(dir[objname] == “down”){
obj[objname].style.height = “1px”;
}
obj[objname].style.display = “block”;
timerID[objname] = setInterval(’slidetick(” + objname + ”);’,timerlen);
}
function slidetick(objname){
var elapsed = (new Date()).getTime() - startTime[objname];
if (elapsed > slideAniLen)
endSlide(objname)
else {
var d =Math.round(elapsed / slideAniLen * endHeight[objname]);
var f =elapsed / slideAniLen;
if(dir[objname] == “up”){
d = endHeight[objname] - d;
f = 1 - f;}
obj[objname].style.height = d + “px”;
obj[objname].style.opacity = f;
obj[objname].style.filter = ‘alpha(opacity=’+(f*100)+’)';
document.getElementById(’searchtextbox’).value=f;
}
return;
}
function endSlide(objname){
clearInterval(timerID[objname]);
if(dir[objname] == “up”){
obj[objname].style.display = “none”;
obj[objname].style.opacity = 0;
obj[objname].style.filter = ‘alpha(opacity=’+(0)+’)';
}
else{
obj[objname].style.opacity = 1;
obj[objname].style.filter = ”;
}
obj[objname].style.height = endHeight[objname] + “px”;
delete(moving[objname]);
delete(timerID[objname]);
delete(startTime[objname]);
delete(endHeight[objname]);
delete(obj[objname]);
delete(dir[objname]);
return;
}
you also need to add some stuff to the div
style=”display:none; overflow:hidden; height:9px;opacity:0.0;filter: alpha(opacity=0);”
March 9th, 2007 at 3:31 pm
[…] such as script.aculo.us. Firblitz posted a nice tutorial, which was initiated by an additional post from Harry […]
March 9th, 2007 at 4:02 pm
[…] - How to Create Sliding, Collapsible Div An article outlining the steps to create a sliding, collapsible div with javascript and css. […]
March 9th, 2007 at 6:54 pm
[…] read more | digg story […]
March 9th, 2007 at 11:54 pm
Awesome, it works on firefox too….
March 10th, 2007 at 10:47 am
[…] Javascript ve CSS ile hazırlanmış güzel bir geçiş efektli açılır menü örneği anlatımı ve kodu. Link […]
March 10th, 2007 at 2:37 pm
I saw your review on John Chow’s site today and wanted to know if you would be interested in a review. Please visit my site for for review exchange rules, let me know if you are interested in a review exchange.
http://jakeldaily.com/?p=42
:ppled fpr your email but did not see it, so decided to leave this in a comment
March 12th, 2007 at 6:59 am
Nice tutorial, only problem is the static height. Pain in the ass if you have dynamic content!
March 12th, 2007 at 3:20 pm
@ Dieter,
Do you know a way around that?
March 12th, 2007 at 8:36 pm
havnt you guys heard of AJAX?
March 13th, 2007 at 5:06 am
it works well but only only by specifying height of the div…..advice me…
March 13th, 2007 at 10:50 am
[…] How to Create an Animated, Sliding, Collapsible DIV with Javascript and CSS […]
March 13th, 2007 at 11:26 am
nice, it works here in any browser.
thanx for sharing it,…
March 13th, 2007 at 5:01 pm
RE: dafin
Apparently you are a little confused yourself. This has nothing to do with AJAX (At all). It is used in conjunction with AJAX, but AJAX doesn’t do the animation. AJAX is a middle layer of communication between the client/server.
Now, prototype.js and scriptaculous do what you are speaking of, and are tied in with most RoR apps and AJAX apps - but they are not the same thing.
March 13th, 2007 at 6:07 pm
@hmaugans: No i don’t but if i find some spare time i’ll take a look at it.
March 13th, 2007 at 10:45 pm
Another thing to keep in mind is that if the user has javascript disabled, they’ll never be able to access the hidden content because the display: none is in the HTML. Better to set both the div’s initial and toggle states via javascript so that if js is disabled, the element will still be visible.
March 14th, 2007 at 3:38 am
Thanks for the tutorial. An easier implementation similar to the “Overlapping Content” script I used on this list -> http://www.mru.ug/index.php?option=weblinks&Itemid=60 Script from dynamic drive
March 14th, 2007 at 4:39 am
is there a way to slide horizontally ? left or right ?
March 14th, 2007 at 11:23 am
function slide(objname){
if(moving[objname])
return;
if(document.getElementById(objname).style.display == “none”)
slidedown(objname);
else
slideup(objname);
}
Use this function to have a single function for sliding up/down
March 14th, 2007 at 11:58 am
Why not just use jQuery?
$(’#div’).fadeIn(speed).slideDown(speed);
Easy!
March 14th, 2007 at 3:03 pm
@Chris,
Read the comments in the Digg article. jQuery would work, but the purpose of this is to be lightweight, lean, and a learning experience.
March 15th, 2007 at 1:01 pm
[…] read more | digg story […]
March 16th, 2007 at 6:46 am
Great example, really slick!
Just wondered about accessibility, does it work without a mouse?
March 17th, 2007 at 3:32 am
Nice tutorial!
March 17th, 2007 at 3:18 pm
Very Nice, This might encourage me to learn more
March 18th, 2007 at 3:38 pm
So how do you to the toggle slide then? maybe you should post a how to for that.
March 19th, 2007 at 12:24 am
[…] the heels of two very successful tutorials on creating a collapsible div and an animated sliding div, I’ve decided to write another. It seems my last few helped a number of programmers learn a […]
March 19th, 2007 at 12:33 am
Coolio!
March 19th, 2007 at 1:08 am
very cool
March 19th, 2007 at 1:31 am
Good job
March 19th, 2007 at 3:54 am
@ Dieter & hmaugans
re: div height & dynamic content
Specify no height for the div to begin with & a style rule of display:none in the stylesheet, then load the dynamic content into the div (since the div is hidden, nothing will show), you can then read the div’s height and assign it to a variable.
e.g. something like this:
var theDiv = document.getElementById(’myDiv’);
var divHite = document.theDiv.scrollHeight;
theDiv.style.height= divHite;
Here’s a full jQuery example. (I know your intent was to show how to code it from start to finish with base javascript, I only provide this example because I recently used it on a site I was working on & hopefully it will convey my idea a bit better)
#ajax-div is given a css rule of display:none; in the stylesheet.
$(’.ajax-div-slide’).click(function() {
$(’#ajax-div’).load(this.href, function() {
var divHite = $(’#ajax-div’).height();
$(’#ajax-div’).height(0).css(”display”, “block”);
$(’#ajax-div’).animate({height: divHite},});
});
return false;
});
March 19th, 2007 at 7:26 am
function slide(objname){
if(moving[objname])
return;
if(document.getElementById(objname).style.display == “none”)
slidedown(objname);
else
slideup(objname);
}
Where do i add that exactly and how do i call the function in a link? Could you explain please.
March 19th, 2007 at 3:26 pm
[…] How to create functions to slide DIVs up and down. It supports multiple animations happening simultaneously, as well as a variable animation length. It’s also time-based, rather than increment based, so it’ll animate the same speed on most computers. [go] […]
March 19th, 2007 at 7:06 pm
Harry,
Sorry it took so long to respond. I wrote about 10 days ago that it wouldn’t work for me in Firefox. I wasn’t totally correct. It works for me on Firefox at home, but not at work? Both are versions 2.0.0.2. I don’t know, maybe its some setting I have… Any ideas. I’m glad I can finally see it now in Firefox!
Scott
March 19th, 2007 at 7:55 pm
@john:
just add that function to the motionpack.js file. change the function in the html to call slide().
watch the quotes around “none” in the new function when copying and pasting.
March 20th, 2007 at 3:21 am
[…] How to Create an Animated, Sliding, Collapsible DIV with Javascript and CSS (tags: css design programming tutorial) […]
March 20th, 2007 at 6:54 am
@alternapop
Thanks for your help. Works now. I dont have any knowledge of Javascript so this entire thing puzzled me, works now though and looks very snazzy.
March 20th, 2007 at 6:56 am
Congrats John, and thanks alternapop!
March 20th, 2007 at 7:17 am
An easier way. Put this script in the page header
function show_hide(the_layer)
{
if(document.getElementById(the_layer))
{
if(document.getElementById(the_layer).style.display == ‘none’)
{
document.getElementById(the_layer).style.display = ‘inline’;
}
else
{
document.getElementById(the_layer).style.display = ‘none’;
}
}
}
and then in the page body put the following
Show/hide some text
This is the Text to show/hide.
The display:none will ensure that the text is hidden on page load.
If you have more than one div you want to show/hide then call them (say) foobar1 and foobar2 etc.
A working example is on my Agatha Christie web site. This has a list of the plots and solutions of all 66 of her full length novels. When viewing the plots the solution is hidden in a foobar div and can be shown/hidden by clicking the link. See it in action at http://www.gbtamc.co.uk/et/index.php?id=644
March 20th, 2007 at 7:22 am
Sorry. Here is the page code.
Show/hide some text
This is the text to show/hide
March 20th, 2007 at 7:28 am
The script
function show_hide(the_layer)
{
if(document.getElementById(the_layer))
{
if(document.getElementById(the_layer).style.display == 'none')
{
document.getElementById(the_layer).style.display = 'inline';
}
else
{
document.getElementById(the_layer).style.display = 'none';
}
}
}
The page details
Show/hide some text
The text to show/hide
March 20th, 2007 at 4:09 pm
Thank you for the tutorial. Good job. How would one toggle the show/hide to make it a + or - depending on the status of the divs visibility? Or say it was collapsed it would say “Show more… ” and if the div was visible it would instead say “Hide details”
March 20th, 2007 at 11:52 pm
Similar to what Tony is asking, how can you configure it so there is only one link instead of two? Click the link once to expand and click it again to close..
March 21st, 2007 at 9:25 am
Very useful, thanks
Exactly what I’ve been looking for.
March 23rd, 2007 at 6:11 am
Excelllent script man…
Works both in IE and FF.
thanx a lot… keep up the good work and write more scripts
March 23rd, 2007 at 3:48 pm
Awsome script, neat, short and easy to understand, not like other script that I have seen before looks very complicated. I am going to use it to hide and show login in form dynamically instead of reloading to another page.
March 24th, 2007 at 11:10 am
Anybody find a way to apply this to a single button? I messed around with it, but I’m not very DOM inclined. And from what I had, I thought it would change out the button once clicked, but it does not. I’d post up the code, but I don’t want to confuse anybody else who might read this later.
March 24th, 2007 at 11:52 am
[…] gotten quite a few comments on my recent post about creating a sliding, collapsible DIV, and while I like to leave some things unsaid, to be figured out by the reader… one question […]
March 24th, 2007 at 11:53 am
Joe, and anyone else asking above. I just made a new post explaining how to do this with a single button (toggle):
http://www.harrymaugans.com/2007/03/24/one-click-toggle-for-sliding-animated-div/
March 25th, 2007 at 6:51 pm
1. Is there any way to use this with a few windows, where opening one would close the others? I’ve gotten it to work on two, but more than two won’t (possibly because I can’t use a list for the slideup function?).
2. Anyone know how to get this to degrade nicely for those who don’t have JavaScript enabled? I’ve seen it done:
http://webassist.com/professional/community/webproresource/masters/client_survey.asp
This one displays all of the divs if js is disabled, one at a time slides in if enabled…
Thanks in advance…
March 27th, 2007 at 7:52 am
I need same thing but left to right , what I have to do and I also want that fading in.
I can use alpha through css, but will that increase or decrease with java if yes then how?
March 27th, 2007 at 11:12 pm
[…] a sliding divs like you see on Digg or many other sites. It was written in response to another tutorial on implementing a similar […]
March 29th, 2007 at 3:21 am
[…] entry by Harry Maugans is far and away one of the best examples of animated DIV tags that I’ve come […]
March 29th, 2007 at 3:23 am
[…] entry by Harry Maugans is far and away one of the best examples of animated DIV tags that I’ve come […]
March 31st, 2007 at 9:04 am
[…] Harry Maugans » How to Create an Animated, Sliding, Collapsible DIV with Javascript and CSS Solo eso. (tags: css javascript ajax) […]
April 3rd, 2007 at 4:28 pm
Harry,
I can’t get the collapsible div to work on IE 6.0 — but it does work on Firefox?
Any fix?
April 5th, 2007 at 7:31 am
Hi there, firstly great little tutorial.
One bug, it doesn’t take into account div padding. Padding changes the viewers perspective of the div’s height and therefore the script should add the padding to the height.
Thanks, Daniel
April 5th, 2007 at 9:30 am
Hello Sir,
Really fond of the information and the quality of information that you have left on your site. I am really obliged by your wish to help people.
Regards,
zombie
April 6th, 2007 at 3:37 am
I guess browser compatibility is a large issue here. Here are the stats so far:
Firefox 1.5: Doesnt work (see comment by tont)
Firefox 2.0.0.3: Works (tested myself)
Internet Explorer 6.0: Doesnt work (see comment by boris)
Internet Explorer 7.0: Works (tested myself)
April 6th, 2007 at 7:44 pm
Would love to get some more details about dynamic height(s) :
As was mentioned :
var theDiv = document.getElementById(’myDiv’);
var divHite = document.theDiv.scrollHeight;
theDiv.style.height= divHite;
But not sure how to implement this…
April 8th, 2007 at 1:51 pm
Wouter,
I was able to get it to work on IE 6.0 by changing around my core stylesheets. There is a good change it had nothing to do with Harry’s code.
April 9th, 2007 at 8:41 am
Harry,
I’m trying to use your script but it’s just not quite working for me, I probably did something wrong but here’s where Im stuck at-
under the
My problem is that when the div is first toggled it slides the entire set height but then disappears almost instantly. When I click again, I get it slides down only to 1px. But when I set the
obj[objname].style.height = “1px”;
that is within the startslide() function to my specified height, it seems to work fine except for the fact that it jumps erratically when toggling down but the animation seems to be fine.
I know I’m not supposed to set it beyond 1px to prevent the erratic jump but it was one of the only things I found to actually display my div!
Do you have any idea what it might be?
April 10th, 2007 at 2:24 am
Great function, I’ve tried to make it a little neater on the vars it uses. I’ve made some big assumptions (ie. using .px but this regex can trim any dimension just change the regex?).
var timers = new Array();
function toggle(elementId){
element = document.getElementById(elementId);
if(element!=null&&timers[elementId]==null){
if(element.style.height.replace(”px”,”")>1){
timers[elementId] = setInterval(”shrink(’”+elementId+”‘)”,5);
}else{
timers[elementId] = setInterval(”grow(’”+elementId+”‘,400)”,5);
}
}
}
function shrink(elementId){
element = document.getElementById(elementId);
if(element!=null){
if(element.style.height.replace(”px”,”")(height-10)){
// clear timer
clearInterval(timers[elementId]);
element.style.height=height;
timers[elementId]=null;
}else{
element.style.height = Math.min(element.style.height.replace(”px”,”")-(-5),height);
}
}else{
clearInterval(timers[elementId]);
}
}
April 11th, 2007 at 12:04 pm
[…] How to Create an Animated, Sliding, Collapsible DIV with Javascript and CSS In this tutorial, we will create functions to slide DIVs up and down. It supports multiple animations happening simultaneously, as well as a variable animation length. It’s also time-based, rather than increment based, so it’ll animate the same speed on most computers; old computers won’t take 10 minutes for a DIV to slide down. […]
April 11th, 2007 at 8:13 pm
Here is a prototyped version of the slider, with dynamic heights and automatic upsliding when 2 divs are attempted to be opened at the same time. Tested in Firefox2 and IE7. Hope you find it useful! Note that you will need to change your div style as well to:
var timerlen = 5;
var slideAniLen = 250;
var timerID = new Array();
var startTime = new Array();
var obj = new Array();
var endHeight = new Array();
var moving = new Array();
var dir = new Array();
function slidedown(objname){
if(moving[objname])
return;
if($(objname).style.height != “0px”)
return; // cannot slide down something that is already visible
$(objname).setStyle({’height’ : $(objname).scrollHeight + ‘px’});
moving[objname] = true;
dir[objname] = “down”;
startslide(objname);
}
function slideup(objname){
if(moving[objname])
return;
if($(objname).style.height == “0px”)
return; // cannot slide up something that is already hidden
moving[objname] = true;
dir[objname] = “up”;
startslide(objname);
}
function startslide(objname){
obj[objname] = $(objname);
endHeight[objname] = parseInt(obj[objname].style.height);
startTime[objname] = (new Date()).getTime();
if(dir[objname] == “down”){
obj[objname].style.height = “1px”;
}
timerID[objname] = setInterval(’slidetick(” + objname + ”);’,timerlen);
}
function slidetick(objname){
var elapsed = (new Date()).getTime() - startTime[objname];
if (elapsed > slideAniLen)
endSlide(objname)
else {
var d =Math.round(elapsed / slideAniLen * endHeight[objname]);
if(dir[objname] == “up”)
d = endHeight[objname] - d;
obj[objname].style.height = d + “px”;
}
return;
}
function endSlide(objname){
clearInterval(timerID[objname]);
if(dir[objname] == “up”)
obj[objname].style.height = “0px”;
delete(moving[objname]);
delete(timerID[objname]);
delete(startTime[objname]);
delete(endHeight[objname]);
delete(obj[objname]);
delete(dir[objname]);
return;
}
function toggleSlide(objname){
if($(objname).style.height == “0px”){
// div is hidden, so let’s slide down
var questions = $(’questions’).getElementsByTagName(’div’);
var questions= $A(questions);
questions.each(function(question){
if(question.style.height != “0px”) slideup(question);
});
slidedown(objname);
}else{
// div is not hidden, so slide up
slideup(objname);
}
}
April 11th, 2007 at 8:15 pm
Sorry, the comment ate the div specifications, here it goes again…
<div id="mydiv" style="display:block; overflow: hidden; height: 0px;">
April 13th, 2007 at 10:57 am
Thanks Harry. First time reader here. I cam because of a comment you left on the digg site (http://digg.com/design/25_Code_Snippets_For_Web_Designers_2) admonishing some troller’s actions; I’m sure glad I did.
Your subscriber tally just got incremented by one!
April 13th, 2007 at 7:21 pm
[…] Harry Maugans » How to Create an Animated, Sliding, Collapsible DIV with Javascript and CSS In this tutorial, we will create functions to slide DIVs up and down. It supports multiple animations happening simultaneously, as well as a variable animation length. It’s also time-based, rather than increment based, so it’ll animate the same speed (tags: blog css design howto) […]
April 13th, 2007 at 9:41 pm
[…] How to Create an Animated, Sliding, Collapsible DIV with Javascript and CSS nice DIV hiding effect using 1 toggle or 2 links, works in FF, IE6, and Opera 9.2 - read comments, exactly what I need for my side project! (tags: Collapsible) […]
April 15th, 2007 at 3:31 am
Hey Harry, nice script.
Just thought I would let you know that you DON’T have to pre-set the height of the div. If you use the Prototype framework, you can use the ‘getHeight’ method, then you can get the height of the div that way. It’s great for divs with dynamic content.
Cheers!
April 15th, 2007 at 6:55 pm
Hi Harry,
Nice script. Thanks.
But I have a situation that I do not want to fix the size of my div. The height is determined at runtime, as it might contain some other elements also (I am developing in c# and will create my div at runtime, based on user option). In that case how to achieve this effect, because without height specified in the style element of the DIV, this script won’t work.
Cheers
April 16th, 2007 at 6:08 am
what should i put in the code to make it work in a php file.it works alone but in the wordpress index file stays dormant.thanks
April 17th, 2007 at 9:26 pm
[…] sliding boxes similar to what Digg uses for it’s comment system. The two more popular ones, How to Create Digg Comment Style Sliding DIVs with Javascript and CSS and Re: How to Create Digg Comment Style Sliding DIVs with Javascript and CSS, failed to take one […]
April 18th, 2007 at 12:43 pm
[…] How to Create an Animated, Sliding, Collapsible DIV with Javascript and CSS In this tutorial, we will create functions to slide DIVs up and down. It supports multiple animations happening simultaneously, as well as a variable animation length. It’s also time-based, rather than increment based, so it’ll animate the same speed on most computers; old computers won’t take 10 minutes for a DIV to slide down. […]
April 21st, 2007 at 11:12 am
I’ve been testing Kosta Krauth’s solution to an equivalent of Accordion. However, I’ve to plug-in prototype.js since it’s a prototype-version. Sadly, the codes don’t work. Even by rewriting to a dynamic height structure to Harry’s solution, that too didn’t work.
Any ideas to get Kosta’s solution to work?
April 22nd, 2007 at 12:03 am
ITs cool script but how can i make it one button that can open and close. istead of seprate two links to do that?
April 27th, 2007 at 11:59 am
[…] http://www.harrymaugans.com/2007/03/06/how-to-creat… - Guide on How to Create an Animated, Sliding, Collapsible DIV with Javascript and CSS […]
April 30th, 2007 at 2:48 am
不错的文章,非常感谢!
May 2nd, 2007 at 4:48 pm
This is pretty neat. Thanks for taking the time to write it up!!!
May 3rd, 2007 at 5:33 am
Great script, but do you know why it flashes once just before it totally dissapears in IE? In FF it isn’t flashing btw.
May 4th, 2007 at 11:37 am
Nice info - very well done.
I am trying to include a .swf element inside of the animated div element. The div animates its transitions in and out just fine - but the swf is not obscured(masked) by the sliding motion, and appears to exist on its own (higher up) z-index. Thus, when the div is sliding up, the swf actually is uneffected until the div is closed completely - then it disappears altogether.
Has anyone come across a work around for this (using a nested swf inside of the target div)
May 5th, 2007 at 8:16 am
So does anyone have a solution for using scrollHeight or any other method to set dynamic heights for each DIV? I’m 99% ready to go with this excellent script, but I’m missing that essential feature — setting heights manually is not an option. I’ve tried to understand how to implement it myself but I fail, miserably…
May 10th, 2007 at 1:57 pm
kk..tteessttiinngg
May 10th, 2007 at 5:17 pm
For those of you who want a SINGLE BUTTON for slide Up and Down
, simply type slideup(objname); in the slidedown function as shown;
function slidedown(objname){
…
if(document.getElementById(objname).style.display != “none”) {
slideup(objname);
return; // cannot slide down something that is already visible
}
…
}
and slidedown(objname); in the slideup function as shown;
function slideup(objname){
…
if(document.getElementById(objname).style.display == “none”) {
slidedown(objname);
return; // cannot slide up something that is already hidden
}
…
}
May 11th, 2007 at 11:51 am
[…] animated sliding boxes similar to what Digg uses for its comment system. The two more popular ones, How to Create Digg Comment Style Sliding DIVs with Javascript and CSS and Re: How to Create Digg Comment Style Sliding DIVs with Javascript and CSS, failed to take one […]