SiteExperts.com Logo Home | Community | Developer's Paradise | Jobs
User Groups | Site Tools | Site Information | Search

Inside Technique : DHTML Scrollbars : Creating the Scrollbar

Once this value is obtained, we can now create the real scrollbar. To create scrollbars, we wrote a createScroll function. This function has 3 required and one optional argument:

scrollbar = createScroll(horizontal, size, 
          increments [, absolute_positioned])

The first argument, horizontal, is a boolean which defines whether a horizontal or vertical scrollbar is being created (true for horizontal, false for vertical). The size specifies how wide or tall a scrollbar to create and increments define the number of steps the scrollbar has starting from 0. The last argument is optional and is used to create absolutely positioned scrollbars. To use CSS-Positioning on your scrollbar, pass true for this argument. This function builds the appropriate HTML and adds it to your document. The return value for this function is the scrollbar element. Below is the complete createScroll() function:

function createScroll(dir, size, max) {
	var outerID = uniqueID("scroll")
	var innerID = uniqueID("spacing")
	var str = ""
	if (null==arrowWidth) getScrollWidth()

	str = "<DIV ID=\"" + outerID + "\" "
	str += "STYLE=\""

	if (dir) 
		str += "width: " + size + ";line-height: 0px;"  + "height: " + arrowWidth
	else 
		str += "height: " + size + ";width: " + arrowWidth
	if (arguments[3]==true)
		str += "; position: absolute"
	str+= "; overflow: auto;\""
	str += "><DIV ID=\"" + innerID + "\" "
	str += "STYLE=\""
	if (dir) 
		str += "width: " + (max-arrowWidth + size)
	else
		str += "height: " + (max + size) + "; width: 0pt"
	str+= "; visibility: hidden\"> </DIV>"
	str += "</DIV>"
	if (document.readyState!="complete")
		document.write(str)
	else
		document.body.insertAdjacentHTML("afterBegin", str)
	return document.all[outerID]
}

This creates a scrollbar with no default action (eg., nothing happens when you scroll). To control the scrollbar, you manipulate the returned element. Since we are using the built-in scrolling that is supported by Internet Explorer, we also get the scroll events and properties for the scrollbars position for free. When an element displays a scrollbar, it automatically exposes an onscroll event, and scrollLeft and scrollTop properties.

Therefore, to add an action to the scrollbar, you just bind to this event:

var h = createScroll(true, 300, 500)

h.scrollLeft = 100  // set an initial value
h.onscroll = doScrolling

If you are running Internet Explorer 4.0, you can see a demonstration that uses horizontal and vertical scrollbars to scale an image. After the demonstration, you can review the complete source code for this example and read why we can't create a Netscape version of the scrollbar.