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

James Robertson http://www.r0bertson.co.uk

« Newer Snippets
Older Snippets »
Showing 1-10 of 16 total  RSS 

Use DHTML to remove an element.

This JavaScript snippet removes an HTML element from it's parent node.

    list_row = document.getElementById('record' + id);
    list_row.parentNode.removeChild(list_row);

Using the mousewheel to zoom in or out an SVG document

This code was originally copied from Mouse wheel programming in JavaScript [adomas.org]. I replaced about 5 lines of code to get the mousewheel controlling the zoom feature in the makeZoom.svg [dzone.com] file.

  /** This is high-level function; REPLACE IT WITH YOUR CODE.
 * It must react to delta being more/less than zero.
 */
function zoomInOut(delta) {
	if (delta >= 0)
		zoomIn()
	else
		zoomOut()
}

function wheel(event){
	var delta = 0;
	if (!event) event = window.event;
	if (event.wheelDelta) {
		delta = event.wheelDelta/120; 
		if (window.opera) delta = -delta;
	} else if (event.detail) {
		delta = -event.detail/3;
	}
	if (delta)
		zoomInOut(delta);
        if (event.preventDefault)
                event.preventDefault();
        event.returnValue = false;
}

/* Initialization code. */
if (window.addEventListener)
	window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel;

Reference of keyCodes

    switch (oEvent.keyCode) {
       case 38: //up arrow  
       case 40: //down arrow
       case 37: //left arrow
       case 39: //right arrow
       case 33: //page up  
       case 34: //page down  
       case 36: //home  
       case 35: //end                  
       case 13: //enter  
       case 9: //tab  
       case 27: //esc  
       case 16: //shift  
       case 17: //ctrl  
       case 18: //alt  
       case 20: //caps lock
       case 8: //backspace  
       case 46: //delete
           return true;
           break;

       default: 

Note: When capturing combination keys there is dedicated boolean attributes for each of the special keys (CTRL, SHIFT, ALT).
Reference: Make Life Easy With Autocomplete Textboxes [JavaScript & AJAX Tutorials] [sitepoint.com]

Create and drag circles in SVG

Demonstrates creating creating and dragging circles using SVG and ECMAScript.

Tested on Firefox 3 beta 4.

file: makeDragDrop.svg
<svg	xmlns="http://www.w3.org/2000/svg" width="100%"
		xmlns:xlink="http://www.w3.org/1999/xlink" >
<script><![CDATA[
var	xmlns="http://www.w3.org/2000/svg"
	xlink="http://www.w3.org/1999/xlink" 
	Root=document.documentElement
standardize(Root)

function standardize(R){
	var Attr={
		"onmouseup":"add(evt)",
		"onmousedown":"grab(evt)",
		"onmousemove":null,
		"onmouseover":"hilight(evt)",
		"onmouseout":"hilight(evt)"
	}
	assignAttr(R,Attr)
}
function hilight(evt){
	var T=evt.target
	if (T.nodeName=="rect") return
	if (evt.type=="mouseover") T.setAttributeNS(null,"stroke-opacity",1)
	else T.setAttributeNS(null,"stroke-opacity",.5)
}
function add(evt){
	if (evt.target.nodeName!="rect") return
	var C=document.createElementNS(xmlns,"circle") 
	var stroke=Color()
	var rad=10+Math.random()*50
	var Attr={
		r:rad,
		cx:evt.clientX,
		cy:evt.clientY,
		"fill": Color(),
		"fill-opacity":.75,
		"stroke": stroke,
		"stroke-opacity":.5,
		"id":stroke,
		"stroke-width":10+Math.random()*(55-rad)
	}
	assignAttr(C,Attr)
	Root.appendChild(C)
}
function grab(evt){
	var O=evt.target
	if (evt.target.nodeName=="rect") return
	var Attr={
		"onmousemove":"slide(evt,'"+O.id+"')",
		"onmouseup":"standardize(Root)"
	}
	assignAttr(Root,Attr)
}
function slide(evt,id){
	var o=document.getElementById(id)
	var c=""; if (o.nodeName=="circle") c="c"
	o.setAttributeNS(null, c+"x", evt.clientX)
	o.setAttributeNS(null, c+"y", evt.clientY)
}
function assignAttr(O,A){
	for (i in A) O.setAttributeNS(null,i, A[i])
}
function Color(){
	return "rgb("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+")"
}
]]>
</script>
<rect width="100%" height="100%" fill="white"/>
<text font-size="12pt" x="50" y="20" id="t1">Click something to move it</text>
<text font-size="12pt" x="80" y="40" id="t2">Click nothing to add something</text>
</svg>

Source file copied from http://srufaculty.sru.edu/david.dailey/svg/makeDragDrop.svg

Capturing the mousemove coordinates

Source code copied from The JavaScript Source: Page Details: Mouse Coordinates [internet.com]
Tested on Firefox.
<!-- ONE STEP TO INSTALL MOUSE COORDINATES:

  1.  Copy the coding into the BODY of your HTML document  -->

<!-- STEP ONE: Paste this code into the BODY of your HTML document  -->

<BODY>

<form name="Show">
X <input type="text" name="MouseX" value="0" size="4"><br>
Y <input type="text" name="MouseY" value="0" size="4"><br>
</form>

<script language="JavaScript1.2">
<!-- Original:  CodeLifter.com (support@codelifter.com) -->
<!-- Web Site:  http://www.codelifter.com -->

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- Begin
  var IE = document.all?true:false;
  if (!IE) document.captureEvents(Event.MOUSEMOVE)
    document.onmousemove = getMouseXY;
    
  var tempX = 0;
  var tempY = 0;
  
  function getMouseXY(e) {
    if (IE) { // grab the x-y pos.s if browser is IE
      tempX = event.clientX + document.body.scrollLeft;
      tempY = event.clientY + document.body.scrollTop;
    }
    else {  // grab the x-y pos.s if browser is NS
      tempX = e.pageX;
      tempY = e.pageY;
    }  
    
    if (tempX < 0){tempX = 0;}
    if (tempY < 0){tempY = 0;}  
    
    document.Show.MouseX.value = tempX;
    document.Show.MouseY.value = tempY;
    
    return true;
  }
//  End -->

<p><center>
<font face="arial, helvetica" size"-2">Free JavaScripts provided<br>
by <a href="http://javascriptsource.com">The JavaScript Source</a></font>
</center><p>

<!-- Script Size:  1.33 KB -->

*update 10:55am 21-Mar-08*
I have decided to use the following code instead as it looks a bit cleaner, and more up-to-date.
Tested on Firefox 2 and IE 6.
document.onmousemove = mouseMove;

function mouseMove(ev){
	ev           = ev || window.event;
	var mousePos = mouseCoords(ev);
}

function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	};
}

Reference: How to Drag and Drop in JavaScript [webreference.com]

'Delete a Twitter entry' dissected

The following code was copied from my Twitter home page, it shows how to delete a twitter entry on the server.

raw HTML code with embedded JavaScript code.

<a href="/status/destroy/719423092" onclick="if (confirm('Sure you want to delete this update? There is NO undo!')) 
{var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 
'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); 
m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild(m);var s = 
document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); 
s.setAttribute('value', 'd0057265c3784d2a6dc6cdb2c26083f638152151'); f.appendChild(s);f.submit(); };return false;" 
title="Delete this update?">


same code as above but with comments.
<a href="/status/destroy/719423092" onclick="

                     // if the user clicks the 'OK' button the confirm function will return true
if (confirm('Sure you want to delete this update? There is NO undo!')) { 

  // -- dhtml: creating html elements on-the-fly -------------------------------
  var f = document.createElement('form'); // create the dhtml 'form' (<form/>) element
  f.style.display = 'none';               // hide the form
  this.parentNode.appendChild(f);         // append the form element to the parent of the current node (<a/>)
  f.method = 'POST';                      // add the method to the form
  f.action = this.href;                   // add the action using the href of the current node (<a/>)
    
  var m = document.createElement('input');   // create the input (<input/>) 'element' 
  m.setAttribute('type', 'hidden');          // set the input type to 'hidden'
  m.setAttribute('name', '_method');         // set the input name to '_method'
  m.setAttribute('value', 'delete');         // set the input value to 'delete'
  f.appendChild(m);                          // append the input element to the form element
  
  var s = document.createElement('input');   // create another input element
  s.setAttribute('type', 'hidden');          // set the type to 'hidden'
  s.setAttribute('name', 'authenticity_token'); // set the name to 'authenticity_token'
  
                                     // set the input element's value using a unique id.
  s.setAttribute('value', 'd0057265c3784d2a6dc6cdb2c26083f638152151'); 
  
  f.appendChild(s);                  // apend the input element to the form element
  // -- end of dhtml: creating html elements on-the-fly -------------------------------
  
  f.submit(); // post the form data back to the server to delete the record, 
              // just as if the user had pressed the submit button.
};

  return false; // returning false cancels the default <a href="..."> request. 
                 // However if JavaScript had been disabled for some reason the 
                 // <a href="..."> would have acted normally, meaning the record 
                 // would have been deleted from following the URL request directly.
 "

Note: Twitter needs JavaScript for the web page to work properly, I've tried and it is not possible to delete a record without JavaScript. The authenticity_token has been altered by me to prevent any malicious activity on my Twitter account.

Encode simple passwords

This code was used to demonstrate how to translate easy to remember simple (weak) passwords into more difficult to guess (strong) passwords. Example: Using Gmail I like an easy to remember password, I submit the password 'jr123' to the password_lookup.html page and what's returned to me is a stronger password 'NCC2SI1T'.

file: passwd_lookup.rb (generates an xml file containing an alphanumeric index with corresponding cryptic values)
class PasswordLookup

  def initialize()
    chars =  (0..9).to_a  + Array.new(7) + ('A'..'Z').to_a + Array.new(6) + ('a'..'z').to_a 
    @chars = (0..9).to_a  + ('A'..'Z').to_a + ('a'..'z').to_a 
    @doc = Document.new()
    root = Element.new('codes')
    @doc.add_element(root)

    chars.each do |char|
      node = Element.new('code')
      if not char.nil? 
        node.attributes['index'] = char
        node.attributes['value'] = get_random_chars(2)
      end
      root.add_element(node)
    end
    puts root
  end

  
  def save(filepath)
    file = File.new(filepath,'w')
    file.puts @doc
    file.close
  end
        
  def get_random_chars(vword_size)
    newpass = Array.new(rand(vword_size) + 1, '').collect{@chars[rand(@chars.size)]}.join
    # return the encryption providing it doesn't already exist in the lookup table.
    if not /value=\'#{newpass}\'/.match @doc.root.elements.to_a.to_s 
     return newpass 
    else
     return get_random_chars(vword_size) 
    end

  end
  
  private :get_random_chars
  
end


output extract: (codes - see also http://rorbuilder.info/pl/codes)
<codes>
<code value='4h' index='a'/><code value='B' index='b'/><code value='m' index='c'/>
<code value='qf' index='d'/>
</codes>


file: password_lookup.js
var t;
var m_doc;

function loadXml() {
  url = 'http://rorbuilder.info/pl/codes';
  m_doc = XML.load(url);
}

function getCode(val,i) {
  pos = val.charCodeAt(i) - 48;
  node = m_doc.documentElement.childNodes[pos]
  return node.getAttribute('value');
}

function timed_update(keyCode,  val) {
  if (val.length > 0 && ((keyCode > 40) || (keyCode == 8)) ) {
    clearTimeout(t);
    t = setTimeout("revealCode('" + val + "')", 1000);
  }
  else
  {  
    o = document.getElementById('out1');
    if (val.length <= 0 && o.value.length > 0) {
      o.value = '';
    }
  }
  
}

function revealCode(val) {
  var iEnd = val.length;
  var newcode = '';
  for (i=0;i<iEnd;i++) {
      
    var codex = getCode(val,i);
    newcode += codex;
  }
  update(newcode);
}

function update(val){
  o = document.getElementById('out1');
  o.value = val;
  /*var o_copied = document.getElementById('out1').createTextRange();
  o_copied.exeCommand("Copy");*/
}


file: password_lookup.html
  <body onload="loadXml()">
    <h1>Password lookup</h1>
    <dl>
    <dt><label for="in1">Enter password:</label></dt>    
    <dd><input type="text" name="in1" id="in1" value="" 
  onkeyup="timed_update(event.keyCode, this.value)" /></dd>
    
    <dt><label for="out1">Generated password</label></dt>
    <dd><input type="text" name="out1" id="out1" value=""/></dd>
    <dd><input type="button" name="clear1" id="clear1" onclick="clearPassword()" value="clear"/></dd>

    </dl>
    <p>see also: <a href="codes.xml" title="password code lookup table">codes.xml</a></p>
  </body>


Try out the encode a simple password demo [rorbuilder.info].

see also: Reading an XML file usng JavaScript [snippets.dzone.com]

Using XPath in JavaScript (Mozilla based)

The following JavaScript code uses XPath to select a specific element. Note: This code works for Firefox, but Internet Explorer has it's own implementation of XPath. see Introduction to using XPath in JavaScript [mozilla.org]

doc (xml document)
<codes>
  <codex value='bQ' index='Q'/>
  <codex value='S' index='R'/>
  <codex value='PU' index='S'/>
  <codex value='ji' index='T'/>
  <codex value='0' index='U'/>
  <codex value='33' index='V'/>
  <codex value='A' index='W'/>
  <codex value='tO' index='X'/>
  <codex value='fW' index='Y'/>
  <codex value='P' index='Z'/>
  <codex value='4h' index='a'/>
  <codex value='B' index='b'/>
  <codex value='m' index='c'/>
  <codex value='qf' index='d'/>
  <codex value='uJ' index='e'/>
</codes>


Assuming the doc object below contains the XML data from above.
var nodesSnapshot = doc.evaluate("codes/codex[@index='a']", doc, null, XPathResult.
  UNORDERED_NODE_SNAPSHOT_TYPE, null );
node = nodesSnapshot.snapshotItem(0);
msg = "The secret code for '" + node.getAttribute('index') + "' is " + node.getAttribute('value');
alert(msg);


output (value from the alert box)
"The secret code for 'a' is 4h"


see also: Reading an XML file using JavaScript

Reading an XML file using JavaScript

Reads an xml file using JavaScript from a web page. Files used: loadxml.js (main script), readxml.js (client script), and readxml.html. The code for loadxml.js was copied from the article JavaScript and XML [devarticles.com]

file: loadxml.js
  XML.load = function(url) {
    var xmldoc = XML.newDocument();
    xmldoc.async = false;  
    xmldoc.load(url);
    return xmldoc;  
  };


XML.newDocument = function(rootTagName, namespaceURL) {
    if (!rootTagName) rootTagName = "";
    if (!namespaceURL) namespaceURL = "";

    if (document.implementation && document.implementation.createDocument) {
        // This is the W3C standard way to do it
        return document.implementation.createDocument(namespaceURL, 
                       rootTagName, null);
    }
    else { // This is the IE way to do it
        // Create an empty document as an ActiveX object
        // If there is no root element, this is all we have to do
        var doc = new ActiveXObject("MSXML2.DOMDocument");

        // If there is a root tag, initialize the document
        if (rootTagName) {
            // Look for a namespace prefix
            var prefix = "";
            var tagname = rootTagName;
            var p = rootTagName.indexOf(':');
            if (p != -1) {
                prefix = rootTagName.substring(0, p);
                tagname = rootTagName.substring(p+1);
            }

            // If we have a namespace, we must have a namespace prefix
            // If we don't have a namespace, we discard any prefix
            if (namespaceURL) {
                if (!prefix) prefix = "a0"; // What Firefox uses
            }
            else prefix = "";

            // Create the root element (with optional namespace) as a
            // string of text
            var text = "<" + (prefix?(prefix+":"):"") + tagname +
                (namespaceURL
                 ?(" xmlns:" + prefix + '="' + namespaceURL +'"')
                 :"") +
                "/>";
            // And parse that text into the empty document
            doc.loadXML(text);
        }
        return doc;
    }
}; 


file: readxml.js
function readXmlFile() {
  url = 'http://rorbuilder.info/pl/test123';

  doc = XML.load(url);
  alert(doc.documentElement.firstChild.nextSibling.firstChild.nodeValue);
}


file: readxml.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Read an XML file</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <script type="text/javascript" src="js/loadxml.js"/>
    <script type="text/javascript" src="js/readxml.js"/>
  </head>

  <body>
    <h1>ReadXML</h1>
    <p>
       If all goes well you should see an alert box display the message 'testing 123'
   </p>
    <p>Press the 'go' button to read the xml file '<a href="test123">test123</a>' 
       from the web server. 
       <input type="button" onclick="readXmlFile()" value="go"/>
    </p>

    
  </body>
</html>


Note: To avoid the cross-site security error message 'permission denied', store all the files on the same web server.

To test the above code try out the demo to read the xml file [rorbuilder.info].

instapaper bookmarklet

Assuming you are registered with the new bookmarking service 'instapaper', then you would use the following code which would normally be placed as a link within your web browser's toolbar.

javascript:var d=document,w=window,e=w.getSelection,k=d.getSelection,x=d.selection,
s=(e?e():(k)?k():(x?x.createRange().text:0)),f='http://www.instapaper.com/b',
l=d.location,e=encodeURIComponent,p='?v=3&u='+e(l.href) +'&t='+e(d.title) +'&s='+e(s),
u=f+p;try{if(!/^(.*\.)?instapaper([^.]*)?$/.test(l.host))throw(0);
iptstbt();}catch(z){a =function(){if(!w.open(u,'t','toolbar=0,resizable=0,status=1,
width=250,height=150'))l.href=u;};if(/Firefox/.test(navigator.userAgent))setTimeout(a,0);
else a();}void(0)


I'm interested in using similar JavaScript if I ever write my own personal bookmarking service.
« Newer Snippets
Older Snippets »
Showing 1-10 of 16 total  RSS