Wednesday, December 9, 2009

Sliding Javascript Menu (onmouseover)

A/N: There is a simpler way of achieving this effect - using JQuery. See post here.

Code is a modification of the one found in http://www.leigeber.com/2008/04/sliding-javascript-dropdown-menu/

(Demo)

<!DOCTYPE
html
PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html>
<
head>
<
title>Sliding popup menu</title>

<
style
type="text/css">

.dropdown
div {position:absolute; overflow:hidden; width:208px; display:none; background:#fff; z-index:200; opacity:0}
</style>

<
script
type="text/javascript">

var DDSPEED = 10;

var DDTIMER = 15;


// main function to handle the mouse events //

function menuEvent(id, d) {

var h = document.getElementById(id + '-header');

var c = document.getElementById(id + '-content');
clearInterval(c.timer);


if (d == 1) {
clearTimeout(h.timer);

if (c.maxh && c.maxh <= c.offsetHeight) { return }

else
if (!c.maxh) {
c.style.display = 'block';
c.style.height = 'auto';
c.maxh = c.offsetHeight;
c.style.height = '0px';
}
c.timer = setInterval(function() { ddSlide(c, 1) }, DDTIMER);
}

else {
h.timer = setTimeout(function() { ddCollapse(c) }, 5000);
}
}


// collapse the menu //

function ddCollapse(c) {
c.timer = setInterval(function() { ddSlide(c, -1) }, DDTIMER);
}


// cancel the collapse if a user rolls over the dropdown //

function cancelHide(id) {

var h = document.getElementById(id + '-ddheader');

var c = document.getElementById(id + '-ddcontent');
clearTimeout(h.timer);
clearInterval(c.timer);

if (c.offsetHeight < c.maxh) {
c.timer = setInterval(function() { ddSlide(c, 1) }, DDTIMER);
}
}


// incrementally expand/contract the dropdown and change the opacity //

function ddSlide(c, d) {

var currh = c.offsetHeight;

var dist;

if (d == 1) {
dist = (Math.round((c.maxh - currh) / DDSPEED));
} else {
dist = (Math.round(currh / DDSPEED));
}

if (dist <= 1 && d == 1) {
dist = 1;
}
c.style.height = currh + (dist * d) + 'px';
c.style.opacity = currh / c.maxh;
c.style.filter = 'alpha(opacity=' + (currh * 100 / c.maxh) + ')';

if ((currh < 2 && d != 1) || (currh > (c.maxh - 2) && d == 1)) {
clearInterval(c.timer);
}
}
</script>
</head>
<body>


<div
class="dropdown">

<a
id="Menu-header"
onmouseover="menuEvent('Menu',1)"
onmouseout="menuEvent('MASMenu',-1)">
Hover to display menu >>

</a>

<div
id="MASMenu-content"
style="display:none;"


onmouseover="cancelHide('MASMenu')"
onmouseout="menuEvent('MASMenu',-1)">

<ul>

<li><a
href="#">Navigation Item 1</a></li>

<li><a
href="#">Navigation Item 2</a></li>

<li><a
href="#">Navigation Item 3</a></li>

<li><a
href="#">Navigation Item 4</a></li>

<li><a
href="#">Navigation Item 5</a></li>

</ul>

</div>
</div>
</
body>
</
html>

No comments:

Post a Comment