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 11-20 of 20 total

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)
   1  
   2  class PasswordLookup
   3  
   4    def initialize()
   5      chars =  (0..9).to_a  + Array.new(7) + ('A'..'Z').to_a + Array.new(6) + ('a'..'z').to_a 
   6      @chars = (0..9).to_a  + ('A'..'Z').to_a + ('a'..'z').to_a 
   7      @doc = Document.new()
   8      root = Element.new('codes')
   9      @doc.add_element(root)
  10  
  11      chars.each do |char|
  12        node = Element.new('code')
  13        if not char.nil? 
  14          node.attributes['index'] = char
  15          node.attributes['value'] = get_random_chars(2)
  16        end
  17        root.add_element(node)
  18      end
  19      puts root
  20    end
  21  
  22    
  23    def save(filepath)
  24      file = File.new(filepath,'w')
  25      file.puts @doc
  26      file.close
  27    end
  28          
  29    def get_random_chars(vword_size)
  30      newpass = Array.new(rand(vword_size) + 1, '').collect{@chars[rand(@chars.size)]}.join
  31      # return the encryption providing it doesn't already exist in the lookup table.
  32      if not /value=\'#{newpass}\'/.match @doc.root.elements.to_a.to_s 
  33       return newpass 
  34      else
  35       return get_random_chars(vword_size) 
  36      end
  37  
  38    end
  39    
  40    private :get_random_chars
  41    
  42  end


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


file: password_lookup.js
   1  
   2  var t;
   3  var m_doc;
   4  
   5  function loadXml() {
   6    url = 'http://rorbuilder.info/pl/codes';
   7    m_doc = XML.load(url);
   8  }
   9  
  10  function getCode(val,i) {
  11    pos = val.charCodeAt(i) - 48;
  12    node = m_doc.documentElement.childNodes[pos]
  13    return node.getAttribute('value');
  14  }
  15  
  16  function timed_update(keyCode,  val) {
  17    if (val.length > 0 && ((keyCode > 40) || (keyCode == 8)) ) {
  18      clearTimeout(t);
  19      t = setTimeout("revealCode('" + val + "')", 1000);
  20    }
  21    else
  22    {  
  23      o = document.getElementById('out1');
  24      if (val.length <= 0 && o.value.length > 0) {
  25        o.value = '';
  26      }
  27    }
  28    
  29  }
  30  
  31  function revealCode(val) {
  32    var iEnd = val.length;
  33    var newcode = '';
  34    for (i=0;i<iEnd;i++) {
  35        
  36      var codex = getCode(val,i);
  37      newcode += codex;
  38    }
  39    update(newcode);
  40  }
  41  
  42  function update(val){
  43    o = document.getElementById('out1');
  44    o.value = val;
  45    /*var o_copied = document.getElementById('out1').createTextRange();
  46    o_copied.exeCommand("Copy");*/
  47  }


file: password_lookup.html
   1  
   2    <body onload="loadXml()">
   3      <h1>Password lookup</h1>
   4      <dl>
   5      <dt><label for="in1">Enter password:</label></dt>    
   6      <dd><input type="text" name="in1" id="in1" value="" 
   7    onkeyup="timed_update(event.keyCode, this.value)" /></dd>
   8      
   9      <dt><label for="out1">Generated password</label></dt>
  10      <dd><input type="text" name="out1" id="out1" value=""/></dd>
  11      <dd><input type="button" name="clear1" id="clear1" onclick="clearPassword()" value="clear"/></dd>
  12  
  13      </dl>
  14      <p>see also: <a href="codes.xml" title="password code lookup table">codes.xml</a></p>
  15    </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)
   1  
   2  <codes>
   3    <codex value='bQ' index='Q'/>
   4    <codex value='S' index='R'/>
   5    <codex value='PU' index='S'/>
   6    <codex value='ji' index='T'/>
   7    <codex value='0' index='U'/>
   8    <codex value='33' index='V'/>
   9    <codex value='A' index='W'/>
  10    <codex value='tO' index='X'/>
  11    <codex value='fW' index='Y'/>
  12    <codex value='P' index='Z'/>
  13    <codex value='4h' index='a'/>
  14    <codex value='B' index='b'/>
  15    <codex value='m' index='c'/>
  16    <codex value='qf' index='d'/>
  17    <codex value='uJ' index='e'/>
  18  </codes>


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


output (value from the alert box)
   1  
   2  "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
   1  
   2    XML.load = function(url) {
   3      var xmldoc = XML.newDocument();
   4      xmldoc.async = false;  
   5      xmldoc.load(url);
   6      return xmldoc;  
   7    };
   8  
   9  
  10  XML.newDocument = function(rootTagName, namespaceURL) {
  11      if (!rootTagName) rootTagName = "";
  12      if (!namespaceURL) namespaceURL = "";
  13  
  14      if (document.implementation && document.implementation.createDocument) {
  15          // This is the W3C standard way to do it
  16          return document.implementation.createDocument(namespaceURL, 
  17                         rootTagName, null);
  18      }
  19      else { // This is the IE way to do it
  20          // Create an empty document as an ActiveX object
  21          // If there is no root element, this is all we have to do
  22          var doc = new ActiveXObject("MSXML2.DOMDocument");
  23  
  24          // If there is a root tag, initialize the document
  25          if (rootTagName) {
  26              // Look for a namespace prefix
  27              var prefix = "";
  28              var tagname = rootTagName;
  29              var p = rootTagName.indexOf(':');
  30              if (p != -1) {
  31                  prefix = rootTagName.substring(0, p);
  32                  tagname = rootTagName.substring(p+1);
  33              }
  34  
  35              // If we have a namespace, we must have a namespace prefix
  36              // If we don't have a namespace, we discard any prefix
  37              if (namespaceURL) {
  38                  if (!prefix) prefix = "a0"; // What Firefox uses
  39              }
  40              else prefix = "";
  41  
  42              // Create the root element (with optional namespace) as a
  43              // string of text
  44              var text = "<" + (prefix?(prefix+":"):"") + tagname +
  45                  (namespaceURL
  46                   ?(" xmlns:" + prefix + '="' + namespaceURL +'"')
  47                   :"") +
  48                  "/>";
  49              // And parse that text into the empty document
  50              doc.loadXML(text);
  51          }
  52          return doc;
  53      }
  54  }; 


file: readxml.js
   1  
   2  function readXmlFile() {
   3    url = 'http://rorbuilder.info/pl/test123';
   4  
   5    doc = XML.load(url);
   6    alert(doc.documentElement.firstChild.nextSibling.firstChild.nodeValue);
   7  }


file: readxml.html
   1  
   2  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   3    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   4  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   5    <head>
   6      <title>Read an XML file</title>
   7      <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
   8      <script type="text/javascript" src="js/loadxml.js"/>
   9      <script type="text/javascript" src="js/readxml.js"/>
  10    </head>
  11  
  12    <body>
  13      <h1>ReadXML</h1>
  14      <p>
  15         If all goes well you should see an alert box display the message 'testing 123'
  16     </p>
  17      <p>Press the 'go' button to read the xml file '<a href="test123">test123</a>' 
  18         from the web server. 
  19         <input type="button" onclick="readXmlFile()" value="go"/>
  20      </p>
  21  
  22      
  23    </body>
  24  </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.

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


I'm interested in using similar JavaScript if I ever write my own personal bookmarking service.

1st attempt at building an autocomplete dhtml user interface

This following html, javascript, and css code is used to build a basic auto-complete user interface. The next step will be to build the back-end server which will handle AJAX requests.

file:autocomplete.html
   1  
   2  <?xml version="1.0" encoding="UTF-8"?>
   3  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   4  <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
   5    <head>
   6      <meta http-equiv="Content-Type" content="text/xml;charset=utf-8" />
   7      <title>auto-complete</title>
   8      <link rel="stylesheet" type="text/css" href="default.css"/>
   9      <script type="text/javascript">
  10        m_i = -1;
  11        m_keyval = '';
  12        
  13        function showResult(keycode){
  14          oresult = document.getElementById('result');
  15          oresult.style.visibility = 'visible';
  16          otext = document.getElementById('tel_search');
  17  
  18          if (keycode =='40'){  // down
  19            if (m_i > 0){
  20              cancelHighlight('i'+m_i);
  21            }
  22            if (m_i < 5){
  23              m_i++;
  24            }
  25            else
  26            {
  27              m_i = 1;
  28            }
  29            highlight('i'+m_i);
  30          }
  31          if (keycode =='38'){  // up
  32            if (m_i > 0 || m_i < 6){
  33              cancelHighlight('i'+m_i);
  34            }
  35            m_i--;
  36            highlight('i'+m_i);
  37          }
  38          if (keycode =='27' || keycode == '39'){   // escape
  39            if (m_keyval != ''){
  40              otext.value = m_keyval;
  41              m_keyval = '';
  42            }
  43            hideResult();
  44            cancelHighlight('i'+m_i);
  45            m_i = 0;
  46          }
  47          if (keycode =='13'){    // enter
  48            itemText = getItem('i'+m_i);
  49            otext.value = itemText;
  50            m_keyval = itemText;
  51          }
  52        }
  53        function setTextValue(i){        
  54          otext = document.getElementById('tel_search');
  55          itemText = getItem('i'+i);
  56          otext.value = itemText;
  57          m_keyval = itemText;
  58          m_i = i;
  59        }
  60        
  61        function hideResult(){
  62          oresult = document.getElementById('result');
  63          oresult.style.visibility = 'hidden';
  64        }
  65  
  66        function getItem(id){
  67          oItem = document.getElementById(id);
  68          return oItem.innerHTML;
  69        }
  70              
  71        function highlight(id){
  72          oItem = document.getElementById(id);
  73          oItem.className = 'highlight';
  74          oItem.style.backgroundColor = '#789';
  75          oItem.style.color = '#ee8';
  76        }
  77        
  78        function cancelHighlight(id){
  79          oItem = document.getElementById(id);
  80          oItem.style.backgroundColor = '#de8';
  81          oItem.style.color = '#bbb';
  82        }
  83        
  84        function mHighlight(i){
  85          if (m_i > 0){
  86            cancelHighlight('i'+m_i);
  87          }
  88          highlight('i'+i);
  89        }
  90        
  91        function handleKeyword(keycode){
  92          if (!(m_i < 0 && keycode == 40) && keycode != 9 && keycode != 37 && !(m_i < 1 && keycode == 38) ) {
  93            showResult(keycode);
  94            if (m_i == -1) m_i = 0;
  95          }
  96          else {
  97            hideResult();
  98          }
  99        }
 100      </script>
 101    </head>
 102    <body onclick="hideResult();">
 103    <div id="search">
 104      <input type="text" id="tel_search" name="tel_search" onkeyup="handleKeyword(event.keyCode);"/>
 105      <p>dhtml is fun </p>
 106      <div id="result">
 107        <ul>
 108          <li id="i1" onmouseover="mHighlight(1);" onmouseout="cancelHighlight('i1');" onclick="setTextValue(1)">1erter</li>
 109          <li id="i2" onmouseover="mHighlight(2);" onmouseout="cancelHighlight('i2');" onclick="setTextValue(2)">2tttye</li>
 110          <li id="i3" onmouseover="mHighlight(3);" onmouseout="cancelHighlight('i3');" onclick="setTextValue(3)">3erter</li>
 111          <li id="i4" onmouseover="mHighlight(4);" onmouseout="cancelHighlight('i4');" onclick="setTextValue(4)">4tttye</li>
 112          <li id="i5" onmouseover="mHighlight(5);" onmouseout="cancelHighlight('i5');" onclick="setTextValue(5)">5erter</li>
 113  
 114        </ul>
 115      </div>
 116    </div>
 117    </body>
 118  </html>

file: default.css
   1  
   2  body {background-color: #e34;}
   3  #search {background-color: #478; height: 4em;position: relative;}
   4  #result {background-color: transparent; max-height: 8em; position: absolute;  overflow: hidden; z-index: 500;left:0; top:1.4em; visibility:hidden; width: 10.2em; padding:0; margin:0;}
   5  #result ul {background-color: #9de; list-style-type: none; padding:0; margin: 0}
   6    #result li {background-color:#de8; color: #bbb; padding:0; margin: 0.2em}
   7      .highlight {background-color: #9ab; cursor: pointer}

Javascript keyCode checker tool

Press any key to determine the javascript key code of that key. This is a simple script:
   1  
   2  <script language="JavaScript">
   3  document.onkeydown = checkKeycode
   4  function checkKeycode(e) {
   5  var keycode;
   6  if (window.event) keycode = window.event.keyCode;
   7  else if (e) keycode = e.which;
   8  alert("keycode: " + keycode);
   9  }
  10  </script>

You may also use this sort of function to disable certain keys, by adding a void(0) in the function as shown. This essentially tells the page to cancel the last event, e.g. the pressing of that certain key. In the example below, the key that is disabled is the enter key.
   1  
   2  <script language="JavaScript">
   3  document.onkeydown = checkKeycode
   4  function checkKeycode(e) {
   5  var keycode;
   6  if (window.event) keycode = window.event.keyCode;
   7  else if (e) keycode = e.which;
   8  if(keycode == 13){
   9  void(0);
  10  }
  11  }
  12  </script>

This text was copied verbatim from the'Javascript keyCode checker tool' page http://www.ryancooper.com/resources/keycode.asp

A JavaScript scroller

A simple scroller written in JavaScript as used on the credits page naming Flock friends & contributors. Source: Within the Flock browser about:credits

   1  
   2       var gCreditsInterval = -1;
   3  
   4        function uninit()
   5        {
   6          if (gCreditsInterval > -1)
   7            clearInterval(gCreditsInterval);
   8        }
   9  
  10        function init()
  11        {
  12          var cb = document.getElementById("creditsBox");
  13          cb.scrollTop = 0;
  14          setTimeout(runCredits, 3000);
  15        }
  16  
  17        function runCredits()
  18        {
  19          gCreditsInterval = setInterval("creditsCallback()", 25);
  20        }
  21  
  22        function creditsCallback()
  23        {
  24          var cb = document.getElementById("creditsBox");
  25          var newtop = cb.scrollTop + 1;
  26          cb.scrollTop = newtop;
  27          if (cb.scrollTop != newtop) {
  28            // we're at the bottom
  29            clearInterval(gCreditsInterval);
  30            setTimeout(function() { cb.scrollTop = 0 }, 10000);
  31          }
  32        }

Keeping the new contents of a growing list in view

The purpose of this code is to demonstrate how to keep the content at the bottom of a list always in view, similar to a chat window. Keywords: div, overflow, scroll, scrolltop. Reference: scrollTop Property http://snipr.com/1wdbn [msdn2.microsoft.com]

   1  
   2  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   3    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   4  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   5    <head>
   6      <title>scrolling div</title>
   7      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
   8      
   9      <style type="text/css">
  10        <!--
  11        body {background-color: #43d;}
  12        div#list  {background-color: #4e8;  overflow: scroll; width: 15em; height: 10em;}
  13        p.other_user {background-color: #af5;}
  14        p {background-color: #ed3;}
  15        -->
  16      </style>
  17      <script type="text/javascript">
  18        function addText() {
  19          olist = document.getElementById('list');
  20          op = document.createElement('p');
  21          op.innerHTML = 'hi';
  22          ocontent = document.getElementById('content');
  23          ocontent.appendChild(op);
  24          olist.scrollTop = olist.scrollHeight;
  25        }
  26      </script>
  27    </head>
  28    <body>
  29      <div id="toolbar"><input type="button" value="add text" onclick="addText()" /></div>
  30      <p>A simple chat style display</p>
  31      <div id="list">
  32        <div id="content">
  33        <p class="other_user">Good <strong>afternoon</strong> how are you?</p>
  34        <p class="other_user">hello?</p>
  35        <p class="other_user">is anybody there?</p>
  36        </div>
  37      </div>    
  38    </body>
  39  </html>

Pull JavaScript code dynamically into your web page at run-time.

Using the JavaScript keyword Eval() with AJAX makes it possible to dynamically add JavaScript code at run-time to your web page.

Here's the complete code dynalert.html, dynalert.js, and dynalert.cgi

file:dynalert.html
   1  
   2  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   3  	"http://www.w3.org/TR/xhtml1-strict.dtd">
   4  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   5  	<head>
   6  		<title>dynalert</title>
   7  		<meta http-equiv="Content-Type" content="type=text/html; charset=ISO-8859-1" />
   8  		<script type="text/javascript" src="dynalert.js"></script>
   9  	</head>
  10  
  11  	<body>
  12  <p id="i1">123 </p><input type="button" value="go" onclick="update()" />
  13  	</body>
  14  </html>


file: dynalert.js
   1  
   2  function populatePage(results){
   3    eval(results);
   4  }
   5  
   6  //send the update
   7  function update() {
   8  
   9  	var strServer = "dynalert.cgi";
  10  	url2 = "";
  11  	SubmitRBData(strServer,"?" + url2);
  12  
  13  }
  14  
  15  function SubmitRBData(strUrl, strPostFields) {
  16  	http.open("GET", strUrl + strPostFields, true);
  17  	http.onreadystatechange = handleHttpResponse;
  18  	http.send(null);
  19  }
  20  function handleHttpResponse() {
  21  
  22  	if (http.readyState == 4) {
  23  		if (http.status == 200)
  24  		{
  25  		results = http.responseText;
  26  		populatePage(results); // string response
  27  		}
  28  	}
  29  
  30  }
  31  
  32  function getHTTPObject() {
  33  
  34  	var objXMLHttp=null
  35  
  36  	if (window.XMLHttpRequest)
  37  	{
  38  		objXMLHttp=new XMLHttpRequest()
  39  	}
  40  	else if (window.ActiveXObject)
  41  	{
  42  		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
  43  	}
  44  
  45  return objXMLHttp
  46  
  47  }
  48  
  49  var http = getHTTPObject(); // We create the HTTP Object


file:dynalert.cgi
   1  
   2  #!/usr/bin/ruby
   3  # dynalert.cgi
   4  
   5  require 'cgi'
   6  
   7  cgi = CGI.new
   8  
   9  #title = cgi['title']
  10  
  11  puts "Content-Type: text/html"
  12  puts
  13  puts "function transcript(){ alert('and Bob said this idea might work.');}"
  14  puts "alert('this is a success');"
  15  puts "alert('we can now pass back anything we like');"
  16  puts "transcript();"
  17  puts "oNew = document.createElement('strong');"
  18  puts "oNew.innerHTML = 'yes - this is bold text';"
  19  puts "document.getElementById('i1').appendChild(oNew);"


Capturing the value from an HTML text box - Ajax style

This extract of JavaScript code illustrates how the value of a text box on an HTML form could be saved efficiently when used with AJAX.
   1  
   2  <input type="text" name="proj1" id="proj1" value="Car_log" 
   3    onkeyup="timed_updateSummaryCRecord(event.keyCode, '1','project', this.value)" />

The onkeyup event retrieves the user input as soon as the key is pressed, then the event.keyCode is validated to ensure only alpha-numeric characters trigger the save routine.
   1  
   2  function timed_updateSummaryCRecord(keyCode, parent_id, field,  val) {
   3    if (val.length > 0 && ((keyCode > 40) || (keyCode == 8)) ) {
   4      clearTimeout(t);
   5      t = setTimeout("updateSummaryCRecord('" + parent_id + "', '" + field + "', '" + val + "')", 1000);
   6    }
   7  }

The setTimeout will trigger the save routine after 1 second, however if the user continues to type before the 1 second timer has elapsed, the running timer will be cancelled and the new timer will start.

Note: keyCode value '8' is accepted because it is the backspace key. It would also be helpful to accept the delete key press.
« Newer Snippets
Older Snippets »
Showing 11-20 of 20 total