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

About this user

brad

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS 

Unobtrusively Executing JavaScript on Page Load

http://simonwillison.net/2004/May/26/addLoadEvent/

The addLoadEvent function takes as an argument another function which should be executed once the page has loaded. Unlike assigning directly to window.onload, the function adds the event in such a way that any previously added onload functions will be executed first.

The way this works is relatively simple: if window.onload has not already been assigned a function, the function passed to addLoadEvent is simply assigned to window.onload. If window.onload has already been set, a brand new function is created which first calls the original onload handler, then calls the new handler afterwards.

addLoadEvent has one very important property: it will work even if something has previously been assigned to window.onload without using addLoadEvent itself. This makes it ideal for use in scripts that may be executing along side other scripts that have already been registered to execute once the page has loaded.

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  }
  else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
  /* more code to run on page load */ 
});

HTML/JavaScript - Select list - Add/Remove Options (DOM)

from http://www.mredkj.com/tutorials/tutorial005.html


Overview

* Insert Before Selected - A new option is created and added above the selected option (as determined by selectedIndex). If none are selected, then no option is added.
* Remove Selected - Deletes the selected option (or options) from the list. If no options are selected, no options are deleted.
* Append Last - No matter what is selected, a new option is added at the end.
* Remove Last - No matter what is selected, the last option is deleted from the list.


Explanation

According to DOM Level 1, the following is the syntax for the add and remove methods in HTMLSelectElement:

void add(in HTMLElement element, in HTMLElement before) raises(DOMException);
void remove(in long index);

The add method takes two arguments: the element to add, and the element to insert before. The spec also says you can add to the end of the list by passing null as the second argument.

The remove method just takes a number: the index of the option to be removed.


The JavaScript
<script language="JavaScript" type="text/javascript">
<!--
var count1 = 0;
var count2 = 0;

function insertOptionBefore(num)
{
  var elSel = document.getElementById('selectX');
  if (elSel.selectedIndex >= 0) {
    var elOptNew = document.createElement('option');
    elOptNew.text = 'Insert' + num;
    elOptNew.value = 'insert' + num;
    var elOptOld = elSel.options[elSel.selectedIndex];  
    try {
      elSel.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
    }
    catch(ex) {
      elSel.add(elOptNew, elSel.selectedIndex); // IE only
    }
  }
}

function removeOptionSelected()
{
  var elSel = document.getElementById('selectX');
  var i;
  for (i = elSel.length - 1; i>=0; i--) {
    if (elSel.options[i].selected) {
      elSel.remove(i);
    }
  }
}

function appendOptionLast(num)
{
  var elOptNew = document.createElement('option');
  elOptNew.text = 'Append' + num;
  elOptNew.value = 'append' + num;
  var elSel = document.getElementById('selectX');

  try {
    elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
  }
  catch(ex) {
    elSel.add(elOptNew); // IE only
  }
}

function removeOptionLast()
{
  var elSel = document.getElementById('selectX');
  if (elSel.length > 0)
  {
    elSel.remove(elSel.length - 1);
  }
}
//-->
</script>



The HTML
<form>
<input type="button" value="o" onclick="insertOptionBefore(count1++);" />
Insert Before Selected<br />
<input type="button" value="o" onclick="removeOptionSelected();" />
Remove Selected<br />
<select id="selectX" size="10" multiple="multiple">
<option value="original1" selected="selected">Orig1</option>
<option value="original2">Orig2</option>
</select>
<br />
<input type="button" value="o" onclick="appendOptionLast(count2++);" />
Append Last<br />
<input type="button" value="o" onclick="removeOptionLast();" />
Remove Last
</form>

Automatic Breadcrumbs

From: http://hyperdisc.unitec.ac.nz/materials/javascript/top10/breadcrumbs.htm

It is possible to hard-code the links in a breadcrumb trail - i.e. to add all the links manually. It is also possible to automatically produce a breadcrumb trail for all pages. This can be done server-side using XSSI, ASP, ColdFusion or PHP. It can also be done client-side using JavaScript.

This is working at the top of every page in the Materials site.

You need to add the function JavaScript to the HEAD of every page and the call to the function in the BODY of every page, wherever you would like the breadcrumb trail to appear. You can add the call to the function multiple times in the same page.

<HEAD>
<script language="JavaScript">
<!-- 
  function breadcrumbs(){
    sURL = new String;
    bits = new Object;
    var x = 0;
    var stop = 0;
    var output = "<div class=topnav><A HREF=/>Hyperdisc</A> &raquo; ";

    sURL = location.href;
    sURL = sURL.slice(8,sURL.length);
    chunkStart = sURL.indexOf("/");
    sURL = sURL.slice(chunkStart+1,sURL.length)

    while(!stop){
      chunkStart = sURL.indexOf("/");
      if (chunkStart != -1){
        bits[x] = sURL.slice(0,chunkStart)
        sURL = sURL.slice(chunkStart+1,sURL.length);
      }else{
        stop = 1;
      }
      x++;
    }

    for(var i in bits){
      output += "<A HREF=\"";
      for(y=1;y<x-i;y++){
        output += "../";
      }
      output += bits[i] + "/\">" + bits[i] + "</A> &raquo; ";
    }
    document.write(output + document.title);
	document.write("</div>");
  }
 // -->
</script>
</HEAD>


<BODY>

<SCRIPT LANGUAGE="JavaScript" TYPE='text/javascript'>breadcrumbs()</SCRIPT>

</BODY>


Points to note about this version of the script:

* It wraps the entire breadcrumb trail in a CSS class called "topnav". You can style this however you like, or you could modify the script to change 'topnav' to any CSS class name you want.
* It names the site "Hyperdisc". You need to modify the script to change the name to something else.
* It assumes that the homepage of the site is in the root directory of the web server. If the homepage of your site is actually in a sub-directory, you would need to seriously modify the script.
* You need to have an index.htm (or equivalent) file in each directory or the user will experience 403 errors.
* Apparantly this script causes errors in older browsers.
* Also note that this script does not work in frames.

javascript - dom method for replacing nodes

In addition to removing nodes, the DOM offers a way to replace one node with another. The replaceChild method accomplishes this. As with removeChild above, replaceChild needs to be called from the element that contains the node you wish to replace.

replaceChild takes two arguments: a reference to the new node, and another to the node being replaced. The following example creates a new SPAN element containing a text node, and uses it to replace an existing SPAN.

<script type="text/javascript">
function replaceSpan(){

    var newSpan = document.createElement("span");
    var newText  
	document.createTextNode("on top of the astounded zebra");
    newSpan.appendChild(newText);

    var para = document.getElementById("example3");
    var spanElm = document.getElementById("ex3Span");
    var replaced = para.replaceChild(newSpan,spanElm);
}
</script>


<p id="example3">The quick brown fox jumps <span id="ex3Span">over the lazy dog</span>.</p>


<button onclick="replaceSpan();">Call replaceSpan()</button>

javascript - dom method for removing nodes

You can remove existing nodes as well as add new ones. The removeChild method allows any node to remove one of its child nodes. Simply pass a reference to the node you wish to remove. Any text or elements within the node being removed will be removed along with it.

<script type="text/javascript">

function removeBElm(){

    var para = document.getElementById("example2");

    var boldElm = document.getElementById("example2B");

    var removed = para.removeChild(boldElm);

}
</script>


<p id="example2"><a href="#" onclick="removeBElm(); return false;">Click this link</a> to see the above script in action.</p>
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS