RationalWiki:Collapsible Comment System/HelperJavascript

From RationalWiki
Jump to navigation Jump to search


function collapsedCommentLinkClickHandler(e) {
	e = e || window.event;
	var eventSource = e.target || e.srcElement;
	
	// firstly, collapse all tables
	var tableIndex = 0;
	var collapsibleButton = document.getElementById("collapseButton" + tableIndex);	

	while (collapsibleButton) {
		if (collapsibleButton.firstChild.data == collapseCaption) {
			collapseTable(tableIndex);
		}
		collapsibleButton = document.getElementById("collapseButton" + ++tableIndex);
	}

	// now, see if we can find the table to which this anchor refers
	var anchorIndex = eventSource.href.indexOf('#');
	if (anchorIndex != -1) {
		var anchorName = eventSource.href.substring(anchorIndex+1);
		var tableDiv = document.getElementById(anchorName);
		if (tableDiv) {
			// look for a collapsible table nested in this div, and expand it
			var tables = tableDiv.getElementsByTagName("table");
			for (var i = 0; i < tables.length; ++i) {
				if (hasClass(tables[i], "collapsible") && tables[i].id.substring(0, 16) == "collapsibleTable") {
					tableIndex = tables[i].id.substring(16);
					collapseTable(tableIndex);
				} 
			}
		}
	}	
}

function addOnclickEventsToCollapsedCommentLinks() {
	var spans = document.getElementsByTagName("span");
	
	for (var i = 0; i < spans.length; ++i) {
		if (spans[i].hasChildNodes() && hasClass(spans[i], "collapsed_comment_link")) {
			// look for links amongst this element's daughter elements
			var daughters = spans[i].getElementsByTagName("a");
			
			for (var j = 0; j < daughters.length; ++j) {
				// add an onclick handler to this anchor
				daughters[j].onclick = collapsedCommentLinkClickHandler;
			}
		}
	}
}

addOnloadHook(addOnclickEventsToCollapsedCommentLinks);