Javascript DHTML Slider WidgetWith a combination of Javascript and CSS, you can capture the mouse click event and make html page elements move.
One useful UI element is a slider widget. It can add the wow factor to an otherwise typical HTML user input interface. First, I had to build a slider handle or knob image: Here is the necessary CSS and HTML: .yg_slider_widget { background: url(zd_slider_widget_bkg.gif) no-repeat; height:26px; } .yg_slider_draggable { position:relative; background: url(zd_slider_widget_knob.gif) no-repeat top; width:16px; height:26px; } <div class=zd_slider_widget> <div class=zd_slider_draggable style='left:20px'> </div> </div> In the CSS and html we are just setting up the look and feel of the slider and its track. Notice the "left:20px" in the html... this is the initial position of the slider knob. The magic of the slider is in the javascript: function fixevent(e) { return (!e) ? window.event : e; } function findtarget(e) { if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement; if (targ.nodeType == 3) // defeat Safari bug targ = targ.parentNode; return targ; } var ZDDrag = { dragobj: false, initx: 0, } function movemouse(e){ e = fixevent(e); if (ZDDrag.dragobj) { lower =0; upper =85; leftval =ZDDrag.initx + e.clientX; leftval = Math.min(leftval,upper); leftval = Math.max(lower,leftval); ZDDrag.dragobj.style["left"] = leftval+"px"; return false; } } function selectmouse(e){ targ = findtarget(e); if (targ.className=="zd_slider_draggable"){ e = fixevent(e); ZDDrag.initx = parseInt(targ.style.left) - e.clientX; ZDDrag.dragobj = targ; document.onmousemove=movemouse; return false; } } document.onmousedown=selectmouse; document.onmouseup= function() { ZDDrag.dragobj=null; }; The functions, fixevent and findtarget are commonly used to resolve discrepancies in the javascript object model for different browsers. In other words, use them if you want you code to work in IE, Firefox, Safari, Opera and Konqueror. The code is fairly straightforward. document.onmousedown=selectmouse, is what associates the function selectmouse with the even onmousedown. The above code saves the x position of the knob at the onmousedown event, and then whenever the mouse moves it repositions the knob to its new x coordinate. Setting the dragobj = null is one way of cancelling the drag. While a useful UI element, it is only useful if you can get the knob's position. That can be done with javascript: alert( parseInt(ZDDrag.dragobj.style.left) ); demo: demo.zip - Download Now Tags: javascript | Related Articles javascript AJAX - Asynchronous Javascript and Xml AJAX Back Button Fix How to properly escape inline javasc... HTML Table Row Highlight Javascript - Drag and Drop Dialog Box Javascript - Objects as Associative ... Javascript Convert Date To String (P... Javascript DHTML Slider Widget Javascript filter search through dat... Parsing XML in Javascript and AJAX |