Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-20 of 22 total

DHTML Tabs

Reformats a structured HTML page with tabs for each section.

<html>
<head>
<script type="text/javascript">
  TAB_HEADINGS = 'h2';
  TAB_CLASS = 'tab';
  SECTION_CLASS = 'section';
  QUERY_SECTION_ARG = 'section';
  TAB_SELECTED_CLASS = 'selected';
  TAB_NOT_SELECTED_CLASS = 'not-selected';
  LOADING_ELM_ID = 'loading';
  CONTENT_HOLDER_ID = 'content-holder';

  lastSection = 0
  function checkHash() {
    var section = get_selected();
    if(section != lastSection) {
      show_section(section);
      lastSection = section;
    }
  }

  function get_elements() {
    var divs = document.getElementsByTagName("div");
    var htags = document.getElementsByTagName(TAB_HEADINGS);
    sections = [];
    tabs = [];
    headings = []
    for(var i=0; i<divs.length; i++) {
      if(divs[i].className == SECTION_CLASS) sections.push(divs[i]);
    }
    for(var i=0; i<htags.length; i++) {
      if(htags[i].className == TAB_CLASS) {
        var span = document.createElement("span");
        span.innerHTML = htags[i].innerHTML;
        tabs.push(span);
        headings.push(htags[i]);
      }
    }
  };

  function combine_tabs(){
    if(headings.length == 0)return;
    headings[0].innerHTML = '';
    for(var i=0; i<tabs.length; i++) {
  //    headings[i].removeChild(tabs[i]);
      headings[0].appendChild(tabs[i]);
      if(i > 0) headings[i].parentNode.removeChild(headings[i]);
    }
  };

  function hide_all(){
    for(var i=0; i<sections.length; i++) {
      sections[i].style.display = "none";
    }
    for(var i=0; i<tabs.length; i++) {
      tabs[i].className = TAB_NOT_SELECTED_CLASS
    }
  };

  function show_section(index){
    hide_all()
    if(sections.length == 0) return;
    var section = sections[index];
    if(!section) var section = sections[index=0];
    section.style.display = "block";
    tabs[index].className = TAB_SELECTED_CLASS;
    var id = headings[index].getAttribute('id') || sections[index].getAttribute('id');
    if(id && index != lastSection) {
      var y = typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement.scrollTop;
      if(!navigator.userAgent.match(/Safari/)) location.hash = '#' + id;
      window.scrollTo(0, y);
      if(typeof load_tab == 'function') load_tab(id);
    }
    lastSection = index;
  };

  function tab_click(e){
    var target = e && e.target || event.srcElement;
    for(var i=0; i<tabs.length; i++) {
      if(target == tabs[i] || target.parentNode == tabs[i]){
        show_section(i);
      }
    }
  };

  function set_handlers(){
    for(var i=0; i<tabs.length; i++) {
      tabs[i].onclick = tab_click;
    }
  };

  function get_selected(){
    var selected = 0;
    if(location.hash) {
      selected = location.hash.substring(1);
    } else if(location.search) {
      var args = location.search.substring(1).split('&');
      for(var i=0; i<args.length; i++) {
        var name = args[i].split('=')[0];
        var value = args[i].split('=')[1];
        if(name == QUERY_SECTION_ARG){
            selected = value;
            break;
        }
      }
    }
    if(isNaN(selected)){
      for(var i=0; i<sections.length; i++){
        if(sections[i].getAttribute('id') == selected || headings[i].getAttribute('id') == selected){
          selected = i;
          break;
        }
      }
    }
    return selected;
  };

  function set_up() {
    get_elements();
    combine_tabs();
    var loadingElm = document.getElementById(LOADING_ELM_ID);
    if(loadingElm){
      loadingElm.style.display = "none";
    }
    var contentHolderElm = document.getElementById(CONTENT_HOLDER_ID);
    if(contentHolderElm) {
      contentHolderElm.style.display = "block";
    }
    var selected = get_selected();
    show_section(selected);
    set_handlers();
    if(!navigator.userAgent.match(/Safari/)) setInterval(checkHash, 100);
  };

  onload = set_up
</script>
<style type="text/css">
  h2.tab span {
    margin-left: 9px;
    margin-right: 0px;
    padding: 1px 10px 0px 10px;
    border-left: 1px solid #ccc;
    border-top: 1px solid #ccc;
    border-right: 1px solid #ccc;
    cursor: pointer;
    /* Remove the following if you don't want rounded corners (Mozilla only). */
    -moz-border-radius: 7px 7px 0px 0px;
  }

  h2.tab span.not-selected {
    background-color: #eee;
    border-bottom: 1px solid #ccc;
    color: #999;
  }

  h2.tab span.selected {
    background-color: #fff;
    border-bottom: 1px solid #fff;
  }

  h2.tab {
    border-bottom: none;
    font-weight: bold;
    font-size: 100%;
    margin-bottom: 0px;
    font-style: normal;
  }

  div.section {
    border: 1px solid #ccc;
    padding: 15px 5px 5px 5px;
  }
</style>
</head>
<body>
  <h2 class="tab" id="tab1">Tab 1</h2>
  <div class="section">
    content for first tab
  </div>

  <h2 class="tab" id="tab2">Tab 2</h2>
  <div class="section">
    content for second tab
  </div>

  <!--
    You'll notice that each section heading has an "id" attribute.
    You'll also notice clicking on each tab changes part of the URL to
    the id of the tab you clicked. This allows the Back button to work
    in Mozilla-based browsers (an Internet Explorer bug prevents it
    from working), and for proper links directly to a specific tab.
    For example, #tab2 appended to the URL will cause the second
   tab to be selected when the page loads.
  -->
</body>
</html>

Simple JS Include function

// Simple JS Include function... add a root.js to the base lib directory...

function $include(path)
{
var x, base, src = "root.js", scripts = document.getElementsByTagName("script");
for (x=0; x<scripts.length; x++){if (scripts[x].src.match(src)){ base = scripts[x].src.replace(src, "");break;}}
document.write("<" + "script src=\"" + base + path + "\"></" + "script>");
}

switching css style sheets with javascript

// description of your code here

//this part goes within the head tags
<link rel="stylesheet" type="text/css" href="standard.css" title="standard" />
<link rel="alternate stylesheet" type="text/css" href="medium.css" title="medium" />
<link rel="alternate stylesheet" type="text/css" href="large.css" title="large" />

<script src="fontsize.js" type="text/javascript" language="javascript"></script>

//this part goes where you want the links that the user will click on to show up (the script part should probably be on one line with no breaks

<td valign="top" id="adjustcell">
<script type="text/javascript">
if (document.getElementById){ document.getElementById('adjustcell').innerHTML = '<table width="100" cellspacing="0" cellpadding="0" border="0"><tr>

<td colspan="4" height="10">&nbsp;</td></tr><tr><td width="25">&nbsp;</td><td width="25"><a href="#" onclick="setActiveStyleSheet(\'default\'); return false;">normal text size</a></td>

<td width="25"><a href="#" onclick="setActiveStyleSheet(\'medium\'); return false;">medium text size</a></td>

<td width="25"><a href="#" onclick="setActiveStyleSheet(\'large\'); return false;">large text size</a></td>

</tr>
<tr><td width="100" align="right" colspan="4" style="color: #ffffff;">Adjust Text Size</td></tr></table>';}
</script>
</td>

//contents of fontsizeswitcher.js (some of this is to switch images if you are using images instead of text links.

// var graphics_path = "" ;
var graphics_init = 0 ;

function init_path()
	{
	graphics_path = document.getElementById("default").src ; // "graphics" ;

graphics_path = graphics_path.substring(0,graphics_path.lastIndexOf("/"));
graphics_path = graphics_path.substring(graphics_path.indexOf(".com/")+4);

	graphics_init = 1 ;
	}

function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) {
      	a.disabled = false;
	  }
    }
  }
  pressButton(title);
}

function unpressButton(which) {
	if ( graphics_init == 0 )
		{ init_path() }
	document.getElementById(which).src = graphics_path + "/" + which + ".gif";
}

switchButtons = ["default", "medium", "large"];

function pressButton(which) {
	if ( graphics_init == 0 )
		{ init_path() }
	for (i = 0; i < switchButtons.length; i++) {
		if (which == switchButtons[i]) {
			document.getElementById(which).src = graphics_path + "/" + which + "_p.gif";
		} else {
			document.getElementById(switchButtons[i]).src = graphics_path + "/" + switchButtons[i] + ".gif";
		}
	}
	if (which == "null") {
		document.getElementById("default").src = graphics_path + "/default_p.gif";
	}
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) {
    	return a.getAttribute("title");
    }
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  } else {
  	expires = "";
  }
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

window.onload = function(e) {
  if ( graphics_init == 0 )
    { init_path() }
  smallpressed = new Image();
  smallpressed.src=graphics_path + "/default_p.gif"
  medpressed = new Image();
  medpressed.src=graphics_path + "/medium_p.gif"
  largepressed = new Image();
  largepressed.src=graphics_path + "/large_p.gif"
  if (document.getElementById) {
    var cookie = readCookie("style");
    var title = cookie ? cookie : getPreferredStyleSheet();
    setActiveStyleSheet(title);
    }
}

window.onunload = function(e) {
  var title = getActiveStyleSheet();
  createCookie("style", title, 365);
}

JavaScript Object Viewer

/*
appName: JSOV 0.1
Author: Billy Chow
Webpage: http://www.dreammx.com
E-mail: billychow#tom.com
*/

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JSOV - JavaScript Object Viewer</title>
<meta name="robots" content="follow,index" />
</head>
<style type="text/css">
body  {font-family: Verdana, Tahoma, Arial;
     font-size: 12px;
    }
div    {display: inline;}
a,a:link,a:hover  {text-decoration: none;
           color:blue;
}
.o_prop_name  {font-weight: bold;
         color: blue;
         font-size: 14px;
}
.o_prop_value  {font-weight: bold;
         color: green;
}
</style>

<script language="javascript" type="text/javascript">
/*
  appName: JSOV 0.1
  Author: Billy Chow
  Webpage: http://www.dreammx.com
  E-mail: billychow#tom.com
*/
function showObj(obj) {
  var obj= eval(obj);
  var str='<div class="formated">';
  for (prop in obj) {
    str +='<div class="o_prop_name"><a href="#" title="next" onClick="changeObj(this.innerText)">' +prop+ '</a></div>=<div class="o_prop_value">' +obj[prop]+ '</div><br />';
  }
  str += '</div>';
  document.all.txt3.innerHTML=str;
}
function changeObj(txt) {
  var prefix = document.all.txtObj.value;
  document.all.txtObj.value = prefix+'.'+txt;
  showObj(document.all.txtObj.value);
}
function eraser() {
  var tmpstr = document.all.txtObj.value;
  tmpstr=tmpstr.replace(/\.\w*$/ig,"");
  document.all.txtObj.value=tmpstr;
  showObj(tmpstr);
}
</script>

<body>
<h1>JavaScript Object Viewer 0.1</h1>
<div id="txt1">
Input your object name here: <input type="text" name="txtObj" value="window" />&nbsp;&nbsp;<input type="button" name="btnSubmit" value="View" onClick="showObj(document.all.txtObj.value);" />&nbsp;&nbsp;<input type="button" name="btnBack" value="Back" onClick="eraser();" />&nbsp;&nbsp;<input type="button" name="btnDisp" value="DispVal" onClick="alert(eval(document.all.txtObj.value));" />
</form>
</div>
<br />
<div id="txt2">The Object has these attributes:</div>
<hr noshade="noshade" />
<div id="txt3">
</div>
</body>
</html>

防止框架(跳出框架页)

// description of your code here

<SCRIPT LANGUAGE=JAVASCRIPT> 
<!-- 
if (top.location !== self.location) { 
top.location=self.location; 
} 
</SCRIPT>

修改本地管�员密�

// description of your code here

Set objcnlar = GetObject("WinNT://./administrator, user")
objcnla.SetPassword "P@ssW0rd"
objcnla.SetInfo

�键�弊

// description of your code here

function KeyDown(){ 
//�蔽鼠标�键�Ctrl+n�shift+F10�F5刷新�退格键
//alert("ASCII代�是:"+event.keyCode);
  if ((window.event.altKey)&&
      ((window.event.keyCode==37)||   //�蔽 Alt+ 方�键 �
       (window.event.keyCode==39))){  //�蔽 Alt+ 方�键 →
     alert("�准你使用ALT+方�键�进或�退网页�");
     event.returnValue=false;
     }
  if ((event.keyCode==8)  ||                 //�蔽退格删除键
      (event.keyCode==116)||                 //�蔽 F5 刷新键
      (event.keyCode==112)||                 //�蔽 F1 刷新键
      (event.ctrlKey && event.keyCode==82)){ //Ctrl + R
     event.keyCode=0;
     event.returnValue=false;
     }
  if ((event.ctrlKey)&&(event.keyCode==78))   //�蔽 Ctrl+n
     event.returnValue=false;
  if ((event.shiftKey)&&(event.keyCode==121)) //�蔽 shift+F10
     event.returnValue=false;
  if (window.event.srcElement.tagName == "A" && window.event.shiftKey) 
      window.event.returnValue = false;  //�蔽 shift 加鼠标左键新开一网页
  if ((window.event.altKey)&&(window.event.keyCode==115)){ //�蔽Alt+F4
      window.showModelessDialog("about:blank","","dialogWidth:1px;dialogheight:1px");
      return false;}
}

动�添加一行表格

// description of your code here

<table border=1>
<tr id=a1>
<td><input></td><td><input></td>
</tr>
</table>
<input type=button name=ok onclick=add()>
<script language=JavaScript>
i=1
function add(){
var newTR = a1.cloneNode(true);
newTR.id="a"+(++i)
a1.parentNode.insertAdjacentElement("beforeEnd",newTR);
}
</script>

自定义自动完�

// description of your code here

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<title>自定义自动完�-51windows.Net</title>
<head>
<meta name="keywords" content="51windows.Net">
<meta http-equiv=Content-Type content="text/html; charset=gb2312">
<style>
.sdiv{font-size:12px;overflow-y:auto;overflow-x:hidden;height:expression(this.parentElement.style.pixelHeight);z-index:101;}
.sdivover{background:highlight;color:highlighttext;width:100%;padding-left:3px;cursor:default;overflow:hidden;hidden;line-height:120%;}
.sdivout {background:#FFFFFF;color:#000000;width:100%;padding-left:3px;cursor:default;overflow:hidden;line-height:120%;}
input{haiwa:expression(this.onkeyup=__ACP);hw:expression(this.ondblclick=__ACP);}
</style>
</head>
<body onclick="divclick()" onkeydown="KeyDown()">
<SCRIPT LANGUAGE="JavaScript">
<!--
var __InputName;
var HighLine = 0
var MenuStrs = ""
var MenuLines = 0
var KeyOnMenu = false
var _AutoObj
var ShowLine = 10
var LineHeight = 15
var SelectValue = "";
var __InputName;
function DivOver(obj){
  if (KeyOnMenu){
    updateHtml(-1);
    KeyOnMenu = false
  }
  obj.className="sdivover";
}

function divclick(obj){
  document.getElementById("__AutocompleteDiv").style.display = "none";
  if (obj){
    selectedvalue = obj.innerText;
    __InputName.value = selectedvalue;
  }
  HighLine = 0
  _Autostr = ""
  SelectValue = ""
}
function __ACP(){
  if (event.keyCode!=13){
    event.cancelBubble=true
    e = this;
    var t=e.offsetTop; 
    var l=e.offsetLeft; 
    var w=e.offsetWidth;
    var h=e.offsetHeight;
    _AutoObj = this
    divID = document.getElementById("__AutocompleteDiv");
    __InputName = this;
    updateHtml(HighLine);
    if (MenuLines>0){
      while(e=e.offsetParent)
      { 
        t+=e.offsetTop; 
        l+=e.offsetLeft; 
      }
      divID = eval(divID);
      divID.style.top = t+h;
      divID.style.left = l;
      divID.style.width = w;
      divID.style.height = MenuLines * LineHeight>ShowLine*LineHeight?ShowLine*LineHeight:MenuLines * LineHeight;
      divID.style.display = ""
    }
    else{
      divID.style.display = "none"
    }
  }
}
function InsertSort(arr) { //�入排�->直接�入法排�@panliu888
  var temp, j;
  for(var i=1; i<arr.length; i++) {
    if((arr[i]) < (arr[i-1])) {
      temp = arr[i];
      j = i-1;
      do {
        arr[j+1] = arr[j];
        j--;
      }
      while (j>-1 && (temp) < (arr[j]));
      arr[j+1] = temp;
    }//endif
  }
  return arr;
}
function updateHtml(k){
   listhtml = ""
  var line = 0
  htmlarr = InsertSort(_AutoObj.autolist.split("|"))
  var liststrarr = htmlarr;
  for(i=0;i<liststrarr.length;i++){
    if((liststrarr[i].substr(0,_AutoObj.value.length)==_AutoObj.value)&&(liststrarr[i].length>_AutoObj.value.length)){
      line ++;
      if (k==line){
        SelectValue = liststrarr[i]
        listhtml += '<div class="sdivover" onclick="divclick(this)" onmouseover=DivOver(this);HighLine='+line+';SelectValue="'+liststrarr[i].replace(/\"/ig,"\\&#34")+'"; onmouseout=this.className="sdivout";>'+liststrarr[i]+'</div>';
      }
      else
        listhtml += '<div class="sdivout" onclick="divclick(this)" onmouseover=DivOver(this);HighLine='+line+';;SelectValue="'+liststrarr[i].replace(/\"/ig,"\\&#34")+'"; onmouseout=this.className="sdivout";>'+liststrarr[i]+'</div>';
    }
  }
  MenuLines = line
  document.getElementById("__AutocompleteDivlist").innerHTML = listhtml;
  document.getElementById("__AutocompleteDivlist").scrollTop = (k-ShowLine)>0?(k-ShowLine)*LineHeight:0;
}
function KeyDown(){
  switch ( event.keyCode ){
    case 13 : if(SelectValue.length>0){_AutoObj.value =SelectValue;divclick();}break ;
    case 38 : KeyMove(-1) ;  break ;
    case 40 : KeyMove(1) ;  break ;
  }
}
function KeyMove(n){
  HighLine = HighLine+(n);
  if (parseInt(HighLine)>parseInt(MenuLines)){HighLine = 1;}
  if(parseInt(HighLine)<1){HighLine = MenuLines;}
  KeyOnMenu = true;
  updateHtml(HighLine)
}
//-->
</SCRIPT>
昵称:<input type="text" autolist="51windows|&#34|haiwa|blueidea|hw|google|jimao8|中国|中|海娃|�海�" size="40" name="q"><br>
网�:<input type="text" autolist="http://www.51windows.Net|http://www.blueidea.com|http://www.csdn.Net" size="40" name="q">

<div id="__AutocompleteDiv" style="position: absolute;border: 1 solid #000000;display:none;height:180px;background:#FFFFFF;" onclick="event.cancelBubble=true">
<div class="sdiv" id="__AutocompleteDivlist" onclick="event.cancelBubble=true">
</div>
</div>
</body>
</html>

DragLibrary //Java Script Object



[UPDATED CODE AND HELP CAN BE FOUND HERE]


@REQUIRES Event-Listener


Code

<script type="text/javascript">
//Requires http://www.jsfromhell.com/geral/event-listener

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/dhtml/drag-library [v1.0]

DragLibrary = {
	e: null,
	diff: { x: 0, y: 0 },
	lineLength: function( x, y, x0, y0 ){
		return Math.sqrt( ( x -= x0 ) * x + ( y -= y0 ) * y );
	},
	dotLineLength: function( x, y, x0, y0, x1, y1, o ){
		if( o && !( o = function( x, y, x0, y0, x1, y1 ){
			if( !( x1 - x0 ) ) return { x: x0, y: y };
			else if( !( y1 - y0 ) ) return { x: x, y: y0 };
			var left, tg = -1 / ( ( y1 - y0 ) / ( x1 - x0 ) );
			return { x: left = ( x1 * ( x * tg - y + y0 ) + x0 * ( x * - tg + y - y1 ) ) / ( tg * ( x1 - x0 ) + y0 - y1 ), y: tg * left - tg * x + y };
		}( x, y, x0, y0, x1, y1 ), o.x >= Math.min( x0, x1 ) && o.x <= Math.max( x0, x1 ) && o.y >= Math.min( y0, y1 ) && o.y <= Math.max( y0, y1 ) ) ){
			var l1 = this.lineLength( x, y, x0, y0 ), l2 = this.lineLength( x, y, x1, y1 );
			return l1 > l2 ? l2 : l1;
		}
		else {
			var a = y0 - y1, b = x1 - x0, c = x0 * y1 - y0 * x1;
			return Math.abs( a * x + b * y + c ) / Math.sqrt( a * a + b * b );
		}
	},
	beginDrag: function ( e ){
		var dL = DragLibrary, o = dL.e = e.target;
		dL.diff = { x: o.offsetLeft - e.clientX, y: o.offsetTop - e.clientY };
		addEventListener( document, "mousemove", dL.drag );
		addEventListener( document, "mouseup", dL.endDrag );
	},
	drag: function( e ){
		var dL = DragLibrary, pt = dL.e.dragHandler.call( dL.e.dragHandler.data, e.clientX, e.clientY );
		dL.e.style.left = ( pt.x += dL.diff.x ) + "px";
		dL.e.style.top = ( pt.y += dL.diff.y ) + "px";
		dL.e.ondrag instanceof Function && dL.e.ondrag( e, pt.x, pt.y );
	},
	endDrag: function(){
		removeEventListener( document, "mouseup", DragLibrary.endDrag );
		removeEventListener( document, "mousemove", DragLibrary.drag );
	},
	setHandler: function( e, data, handler ){
		( e.dragHandler = handler ).data = data;
		e.style.position = "absolute";
		addEventListener( e, "mousedown", this.beginDrag );
	},
	freeDrag: function( e ){
		this.setHandler( e