Make toc in a wiki draggable

From About PCs Wiki
Revision as of 05:32, 15 June 2021 by Lily (talk | contribs) (Created page with "{{Help:Make table of contents draggable}}")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Idea[edit | hide]

The standard content table on a wiki page is at top of the site and vanishes when scrolling down. This means that this content table does not much good in a long page with many headers, just look into this page. The following simple code procudes a content table with a fixed position on the right top (you may change this behaviour if you do not like this specific position).

Code[edit | hide]

$(function() {
	//make TOC draggable
	var $mytoc = $('#toc');
	if ( $mytoc.length ) {
		var pos = $mytoc.position();
		$mytoc.css({ 'position': 'absolute',
			marginLeft: 0, marginTop: 0,
			top: pos.top, left: pos.left
		});
		dragElement($mytoc[0]);
		setTimeout(function () {
			$('#toc').css({
				'position': 'fixed',
				'right': '0.5em'
			});
		}, 200);
	}

	function dragElement(elmnt) {
		var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
		elmnt.onmousedown = dragMouseDown;
		function dragMouseDown(e) {
			e = e || window.event;
			e.preventDefault();
			// get the mouse cursor position at startup:
			pos3 = e.clientX;
			pos4 = e.clientY;
			document.onmouseup = closeDragElement;
			// call a function whenever the cursor moves:
			document.onmousemove = elementDrag;	
			//console.log('MediaWiki:Gadget-Navbar.js dragMouseDown');
		}
		
		function elementDrag(e) {
			e = e || window.event;
			e.preventDefault();
			// calculate the new cursor position:
			pos1 = pos3 - e.clientX;
			pos2 = pos4 - e.clientY;
			pos3 = e.clientX;
			pos4 = e.clientY;
			// set the element's new position:
			elmnt.style.top = elmnt.offsetTop - pos2 + 'px';
			elmnt.style.left = elmnt.offsetLeft - pos1 + 'px';	
			//console.log('MediaWiki:Gadget-Navbar.js elementDrag');
		}
		function closeDragElement() {
			// stop moving when mouse button is released:
			document.onmouseup = null;
			document.onmousemove = null;	
			//console.log('MediaWiki:Gadget-Navbar.js closeDragElement');
		}
	}
});

Links[edit | hide]