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 1-10 of 22 total  RSS 

'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.

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
<?xml version="1.0" encoding="UTF-8"?>
<!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" lang="en" xml:lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/xml;charset=utf-8" />
    <title>auto-complete</title>
    <link rel="stylesheet" type="text/css" href="default.css"/>
    <script type="text/javascript">
      m_i = -1;
      m_keyval = '';
      
      function showResult(keycode){
        oresult = document.getElementById('result');
        oresult.style.visibility = 'visible';
        otext = document.getElementById('tel_search');

        if (keycode =='40'){  // down
          if (m_i > 0){
            cancelHighlight('i'+m_i);
          }
          if (m_i < 5){
            m_i++;
          }
          else
          {
            m_i = 1;
          }
          highlight('i'+m_i);
        }
        if (keycode =='38'){  // up
          if (m_i > 0 || m_i < 6){
            cancelHighlight('i'+m_i);
          }
          m_i--;
          highlight('i'+m_i);
        }
        if (keycode =='27' || keycode == '39'){   // escape
          if (m_keyval != ''){
            otext.value = m_keyval;
            m_keyval = '';
          }
          hideResult();
          cancelHighlight('i'+m_i);
          m_i = 0;
        }
        if (keycode =='13'){    // enter
          itemText = getItem('i'+m_i);
          otext.value = itemText;
          m_keyval = itemText;
        }
      }
      function setTextValue(i){        
        otext = document.getElementById('tel_search');
        itemText = getItem('i'+i);
        otext.value = itemText;
        m_keyval = itemText;
        m_i = i;
      }
      
      function hideResult(){
        oresult = document.getElementById('result');
        oresult.style.visibility = 'hidden';
      }

      function getItem(id){
        oItem = document.getElementById(id);
        return oItem.innerHTML;
      }
            
      function highlight(id){
        oItem = document.getElementById(id);
        oItem.className = 'highlight';
        oItem.style.backgroundColor = '#789';
        oItem.style.color = '#ee8';
      }
      
      function cancelHighlight(id){
        oItem = document.getElementById(id);
        oItem.style.backgroundColor = '#de8';
        oItem.style.color = '#bbb';
      }
      
      function mHighlight(i){
        if (m_i > 0){
          cancelHighlight('i'+m_i);
        }
        highlight('i'+i);
      }
      
      function handleKeyword(keycode){
        if (!(m_i < 0 && keycode == 40) && keycode != 9 && keycode != 37 && !(m_i < 1 && keycode == 38) ) {
          showResult(keycode);
          if (m_i == -1) m_i = 0;
        }
        else {
          hideResult();
        }
      }
    </script>
  </head>
  <body onclick="hideResult();">
  <div id="search">
    <input type="text" id="tel_search" name="tel_search" onkeyup="handleKeyword(event.keyCode);"/>
    <p>dhtml is fun </p>
    <div id="result">
      <ul>
        <li id="i1" onmouseover="mHighlight(1);" onmouseout="cancelHighlight('i1');" onclick="setTextValue(1)">1erter</li>
        <li id="i2" onmouseover="mHighlight(2);" onmouseout="cancelHighlight('i2');" onclick="setTextValue(2)">2tttye</li>
        <li id="i3" onmouseover="mHighlight(3);" onmouseout="cancelHighlight('i3');" onclick="setTextValue(3)">3erter</li>
        <li id="i4" onmouseover="mHighlight(4);" onmouseout="cancelHighlight('i4');" onclick="setTextValue(4)">4tttye</li>
        <li id="i5" onmouseover="mHighlight(5);" onmouseout="cancelHighlight('i5');" onclick="setTextValue(5)">5erter</li>

      </ul>
    </div>
  </div>
  </body>
</html>

file: default.css
body {background-color: #e34;}
#search {background-color: #478; height: 4em;position: relative;}
#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;}
#result ul {background-color: #9de; list-style-type: none; padding:0; margin: 0}
  #result li {background-color:#de8; color: #bbb; padding:0; margin: 0.2em}
    .highlight {background-color: #9ab; cursor: pointer}

Dynamic Select Example

// Example of JavaScript to with with Select Options

<html>
<head>
	<title>test</title>	
</head>
<body id="test" onload="">
	<form>
		<select id="lstStuff" multiple="multiple" onChange="lstStuff_OnChange()" size="6" style="width:200px;">
			<option>item 1</option>
			<option>item 2</option>
			<option>item 3</option>
			<option>item 4</option>
			<option>item 5</option>
			<option>item 6</option>			
		</select>	
		<br/>
		<a href="javascript:selectAll('lstStuff', true);">all</a>
		<a href="javascript:selectAll('lstStuff', false);">none</a>
		<p/>
		<select id="lstOtherStuff" multiple="multiple" size="6" style="width:200px;">
		</select>
		<br/>
		<a href="javascript:selectAll('lstOtherStuff', true);">all</a>
		<a href="javascript:selectAll('lstOtherStuff', false);">none</a>
	</form>
	<script type="text/javascript" charset="utf-8">
		var otherStuff = {
			"item 1" : [ "subitem 1.1", "subitem 1.2", "subitem 1.3", "subitem 1.4" ],
			"item 2" : [ "subitem 2.1", "subitem 2.2" ],
			"item 4" : [ "subitem 4" ],
			"item 6" : [ "subitem 6.1", "subitem 6.2" ]
		};
	</script>
	<script type="text/javascript" charset="utf-8">
		function selectAll(listName, selected) {
			var listBox = document.getElementById(listName);
			for(i=0; i<listBox.length; i++) {
				listBox.options[i].selected=selected;
			}
			if( listBox.onchange ) {
				listBox.onchange();
			}
		}
		function lstStuff_OnChange() {
			var listBox = document.getElementById("lstStuff");
			var subListBox = document.getElementById("lstOtherStuff");
			subListBox.options.length=0;
			for(i=0; i<listBox.length; i++) {
				if( listBox.options[i].selected ) {
					var key = listBox.options[i].text;
					if(otherStuff[key]) {
						for(j=0; j<otherStuff[key].length; j++) {
							subListBox.options.add(new Option(otherStuff[key][j],otherStuff[key][j]));
						}
					}
				}
			}
		}
	</script>
</body>
</html>

Dynamic Modification of CSS Class Properties

Modifying the rendering of an element with an ID is relatively easy using document.getElementById. Modifying the attributes fo an entire class dynamically is a little more code, but the DOM does provide the means to do it through the stylesheet object; with some cross-browser variations.

For additional CSS and HTML see some of the full length articles
Written by IT professionals from Experts Round Table

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<head>
<title> Fragment</title>
<style type="text/css">
A.topLinks {font-weight:bold}
.Borders {font-weight:bold}
</style>
<script type="text/javascript">
function modRule()
{
	if (!document.styleSheets) return;
	var thecss = new Array();
	if (document.styleSheets[0].cssRules)  // Standards Compliant
        {
	   thecss = document.styleSheets[0].cssRules;
        }
	else
        {         
           thecss = document.styleSheets[0].rules;  // IE 
        }
        for (i=0;i<thecss.length;i++)
        {
           if ((thecss[i].selectorText.toLowerCase()=='a.toplinks') || (thecss[i].selectorText.toLowerCase()=='.borders'))
           {
	     thecss[i].style.cssText="font-weight:normal; color:red";
           }
        }
}
</script>
</head>
<body>
<a href="#" class="topLinks" onclick="modRule();return false;">click here</a>
<div class="Borders"> hello world. <span style="color:blue">All of your bases are belong to us.</span> </div>
</body>
</html>


Notice that the color of the text in the span is not changed, because the inline style prevails over the class in the stylesheet. This technique can be used to make on the fly changes to the look and feel of a page in response to events or user input.

Setting Element Height Dynamically

There are times when you need to control the height of an element based on the screen size. However youcan control the user setup, and of course there are browser differences so this snippet handles browser and object detection and sets the height during page load and for any re-sizing event.

An example of the snippet in action

  var minorOffset = (document.all)? 25 : 38;
   function setHgt()
   {
      var sHGT;
      srcobj=document.getElementById('main');
      if (self.innerHeight)
      {
	   sHGT = self.innerHeight;
	}
      else
      { 
         if (document.documentElement && document.documentElement.clientHeight)
         {
	      sHGT = document.documentElement.clientHeight;
         }
         else
         {
            if (document.body)
            {
              sHGT = document.body.clientHeight;
            }
         }
      }
      sHGT=sHGT-(document.getElementById('main').offsetTop+minorOffset);
  document.getElementById('main').style.height=sHGT+"px";
   }
window.onload=setHgt;
window.onresize=setHgt;

Typed Tooltip Effect

This simple bit of scripting will create a dynamic typing effect for your tool tips.
The script can be
seen implemented here



var str='';
var obj='false';
var pntr='';
var cnt=0;
var textArr = new Array(5);
textArr[0] = "All your bases are belong to us!";
textArr[1] = "The answer is 42; of course.";
textArr[2] = "The end of the universe will be the result of a mis-calculation in the core.";
textArr[3] = "I don't believe its alive; but it thinks it is.";
textArr[4] = "About 10 seconds after you open it; you'll wish you hadn't";

function looptext()
{
   obj.innerHTML=str.substr(0,cnt);
   cnt++;
   if (cnt<=str.length) setTimeout('looptext()',100);
}

function typeText(lnk,lyr)
{
   str=textArr[lyr];
   pntr= 'lyr'+lyr;
   obj=document.getElementById(pntr);
   obj.style.left=(lnk.offsetLeft+30)+'px';
   obj.style.top=(lnk.offsetTop+25)+'px';
   obj.style.display='block';
   cnt=1;
   looptext();
}

function clearText(lyr)
{
   cnt=2500;
   pntr='lyr'+lyr;
   obj=document.getElementById(pntr);
   obj.style.display='none';
   obj.style.left='-50px';
   obj.style.top='-50px';
   obj.innerHTML='&nbsp;';
}


The links using the effect are done this way:

   <a href="javascript:alert('no page linked')"
      onmouseover="typeText(this,2)"
      onmouseout="clearText(2)"
      onclick="clearText(2)"> 
   This is link Three
   </a>

Expand and collapse effect for data grids

This is a little use of dynamic CSS to create expandable, and collapsible sections in data grid presentations.
Cd&
Experts Round Table


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html>
<head>
<style type="text/CSS">
   table {
          width:100%; 
          border-collapse:collapse;
          border:2px solid silver;
         }
   tbody {
          display:block
         }
   th {
       font-weight:normal;
       text-align:left;
      }
   td {
       text-align:center;
       padding:8px;
       border:1px solid silver; }
   .linkspan {
              color:gold;
              background-color:blue;
              font-weight:bold;
              text-decoration:none;
              padding:0 2px; 
              font-size:1.2em;
              margin:right:3px;
             }
   .vis {
         display:block;
        }
</style> 

<script type="text/javascript"> 
   var ELpntr=false;
   function hideall()
   {
      locl = document.getElementsByTagName('tbody');
      for (i=0;i<locl.length;i++)
      {
         locl[i].style.display='none';
      }
   }

   function showHide(EL,PM)
   {
      ELpntr=document.getElementById(EL);
      if (ELpntr.style.display=='none')
      {
         document.getElementById(PM).innerHTML=' - ';
         ELpntr.style.display='block';
      }
      else
      {
         document.getElementById(PM).innerHTML=' + ';
         ELpntr.style.display='none';
      }
   }
   onload=hideall;
</script>
</head> 
<body> 
<table>
   <thead>
   <tr class="vis"> <th colspan="3"><a href="#" 
      onclick="showHide('fruit','fruitspan')">
        <span id="fruitspan" class="linkspan"> + </span> Fruit:</a></th></tr>
   </thead> 
   <tbody id="fruit">
      <tr> <td> Apple</td><td> Red</td><td> Shiny</td></tr>
      <tr> <td> Pear</td><td> Green</td><td> Firm</td></tr>
      <tr> <td> Banana</td><td> Red</td><td> Shiny</td></tr>
   </tbody>
</table>
<table>
   <thead>
   <tr class="vis"> <th colspan="3"><a href="#" onclick="showHide('vegtable','vegtablespan')">
        <span id="vegtablespan" class="linkspan"> + </span> Vegtable:</a></th></tr> 
   </thead>
   <tbody id="vegtable">
      <tr> <td> Carrot</td><td> Orange</td><td> Crisp</td></tr>
      <tr> <td> Cucumber</td><td> Green</td><td> Delicious</td></tr>
      <tr> <td> Cauliflower</td><td> White</td><td> Firm</td></tr>
   </tbody>
</table>
<table>
   <thead>
   <tr class="vis"> <th colspan="3"><a href="#" onclick="showHide('animal','animalspan')">
        <span id="animalspan" class="linkspan"> + </span> Animal:</a></th></tr>
   </thead> 
   <tbody id="animal">
      <tr> <td> Cat</td><td> Calico</td><td> Lazy</td></tr>
      <tr> <td> Dog</td><td> Retriever</td><td> Golden</td></tr>
      <tr> <td> Badger</td><td> Muddy</td><td> Mean</td></tr>
   </tbody>
</table> 
</body> 
</html> 

Passing parameters between pages without servers side scripting

// description of your code here
Sometimes you need to pass parameters directly between pages for dynamic effect. This is the way to process those on the receiving page. The arguments can be added directly onto the url or a form with a get method caa be used. As long as the server just passs the request through the receiving page can use the parameters to present alternate presentations, pre-populate form eleemnts, or just carry through the values for a multi-page form.

Cd&
Experts Round Table

<html> 
<head> 
<script type="text/javascript"> 
   parmarr = new Array;
   valuearr = new Array;
   function readparms()
   {
      if(location.search!='')
      { 
         Args = location.search.substring(1); 
         parmarr = Args.split('&');
         for(i=0;i<parmarr.length;i++)
         {
            valuearr[i] = parmarr[i].split('='); 
         }
      } 
   }
</script> 
</head> 
<body onLoad="readparms();showparms();"> 
<script type="text/javascript">
   // all this script does is display the parms but the
   // stored values can be used by any function
   function showparms()
   { 
      if(location.search!='')
      { 
         for(i=0;i<valuearr.length;i++)
         {
            document.write(valuearr[i][0] +'=' +valuearr[i][1] +'<br>'); 
         }
      } 
   } 
</script>  
</body> 
</html>

Add Rows to an HTML table Dynamically

// description of your code here
This script modifies an existing table in a page using
the DOM methods to add rows

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html>
<head>
<script type="text/javascript">
function addRow(content,morecontent)
{
         if (!document.getElementsByTagName) return;
         tabBody=document.getElementsByTagName("TBODY").item(0);
         row=document.createElement("TR");
         cell1 = document.createElement("TD");
         cell2 = document.createElement("TD");
         textnode1=document.createTextNode(content);
         textnode2=document.createTextNode(morecontent);
         cell1.appendChild(textnode1);
         cell2.appendChild(textnode2);
         row.appendChild(cell1);
         row.appendChild(cell2);
         tabBody.appendChild(row);
       
   
}
</script>
</head>
<body>
<table border='1' id='mytable'>
<tbody>
<tr><td>22</td><td>333</td></tr>
<tr><td>22</td><td>333</td></tr>
</tbody>
</table>
<button onClick='addRow("123","456");return false;'>
Add Row</button>
</body>
</html>

Javascript to put a hotkey on a Web Page

// description of your code here
This page will fire an event when the key specified in the
variable key1 is pressed.

Cd&
http://www.expertsrt.com

var key1="32";
var x='';
function handler(e) 
{
  if (document.all) {
  var evnt = window.event; 
  x=evnt.keyCode;
}
else
x=e.charCode;
if (x==key1) location.href='http://www.expertsrt.com';
}
if (!document.all){
window.captureEvents(Event.KEYPRESS);
window.onkeypress=handler;
}
else
{
document.onkeypress = handler;
} 
« Newer Snippets
Older Snippets »
Showing 1-10 of 22 total  RSS