Tuesday, March 27, 2007

Creating sliding DIVs

Here is a tutorial for writing a sliding divs like you see on Digg or many other sites. It was written in response to another tutorial on implementing a similar behavior.

Both articles are worth reading as it spells out clearly how to do the effect. The version on firblitz takes a more object oriented approach. In both examples, the initial call is from an inline Javascript (a href="javascript:..."). There is nothing wrong with doing this, but to have an even cleaner separation between Javascript and the HTML presentation, it's best to not have inline Javascript at all. Instead, use the event model to attach the function to the event so that that the HTML is completely clean.

Start with the following addition to firblitz's javascript code.




function toggle() {
var sd = document.getElementById("slidediv");
if (sd.style.display == 'none') {
Slide('slidediv').down();
} else {
Slide('slidediv').up();
}
}
function init() {
// attach event listener to objects
var slidediv = document.getElementById("mydiv");
slidediv.addEventListener("click", toggle, true);
}
window.onload = init;



And the body of the html would just be:



clickme





To take it one step further, take out the inline styles. However, this introduced one problem. Javascripts is unable to access the style value directly if it is not an inline style. This is because the element's style is not the style of the CSS object that is assigned through the #id. Thus, you have to manually assign the styles to the element. This is the end result:



function toggle() {
var sd = document.getElementById("slidediv");
var styles = getComputedStyle(sd, '');
sd.style.display = styles.display;
sd.style.height = styles.height;
if (sd.style.display == 'none') {
Slide('slidediv').down();
} else {
Slide('slidediv').up();
}
}
function init() {
// attach event listener to objects
var slidediv = document.getElementById("mydiv");
slidediv.addEventListener("click", toggle, true);
}



And the body of the html is a clean:



clickme

Hello world!


No comments:

Post a Comment