faqts : Computers : Programming : Languages : JavaScript : DHTML

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

13 of 18 people (72%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

How can I drag a layer up and down like a scrollbar?

Mar 4th, 2001 09:18
Martin Honnen,


The following example code works with IE4+, NN4, NN6 and Opera 5:
<HTML>
<HEAD>
<STYLE>
#aDiv {
  position: absolute;
  left: 200px;
  top: 0px;
  width: 20px;
  height: 100px;
  background-color: blue;
  layer-background-color: blue;
}
</STYLE>
<SCRIPT>
var dragElement;
var elY;
var mouseDownY;
function getPageY (element) {
  var y = 0;
  do 
    y += element.offsetTop;
  while ((element = element.offsetParent));
  return y;
}
function startDrag (element, evt) {
  dragElement = element;
  if (document.layers) {
    elY = dragElement.top;
    mouseDownY = evt.pageY;
    document.captureEvents(Event.MOUSEMOVE);
  }
  else if (document.all || document.getElementById) {
    elY = getPageY (dragElement);
    mouseDownY = evt.clientY;
  }
  document.onmousemove = drag;
}
function drag (evt) {
  if (document.layers)
    dragElement.top = elY + evt.pageY - mouseDownY;
  else if (document.all)
    dragElement.style.pixelTop = elY + event.clientY - mouseDownY;
  else if (document.getElementById)
    dragElement.style.top = (elY + evt.clientY - mouseDownY) + 'px';
}
function stopDrag () {
  document.onmousemove = null;
  dragElement = null;
  if (document.layers)
    document.releaseEvents(Event.MOUSEMOVE);
}
</SCRIPT>
</HEAD>
<BODY>
<DIV ID="aDiv"
     ONMOUSEDOWN="startDrag(this, event);"
     ONMOUSEUP="stopDrag();"
></DIV>
<SCRIPT>
if (document.layers) {
  document.aDiv.clip.width = 20;
  document.aDiv.clip.height = 100;
  document.aDiv.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);
  document.aDiv.onmousedown = function (evt) {
    startDrag(this, evt);
  };
  document.aDiv.onmouseup = function (evt) {
    stopDrag();
  };
}
</SCRIPT>
</BODY>
</HTML>