Author Archive

Move Images using Javascript

Next javascript code shows how you can move images around the page.

Compatibility: Mozilla, Opera, Chrome, Safari

Code:

 var curElement;
 function doMouseMove(e)
 {
   var newleft = 0, newTop = 0;
   curElement.style.position = "absolute";
   if((e.which == 1) && (curElement != null))
   {
     newleft = e.screenX - (curElement.offsetWidth/2);
     curElement.style.left = newleft + "px";
     newtop = e.screenY - (curElement.offsetHeight/2);
    curElement.style.top = newtop + "px";
   }
 }

 function doDragStart(e)
 {
   // Don't do default drag operation.
   if ("IMG" == e.target.tagName)
   {
     e.returnValue = false;
   }  
 }

 function doMouseDown(e)
 {
   if ((e.which == 1) && (e.target.tagName == "IMG"))
   {
     curElement = e.target;
   }
 }

 function dropElem()
 {
   curElement = null;
 }    

 document.ondragstart = doDragStart;
 document.onmousedown = doMouseDown;
 document.onmousemove = doMouseMove;
 document.onmouseup   = dropElem;

To expirement with it create an HTML document and put the code in the head element, the body element must contains at least one img element, good luck.


offsetLeft - offsetTop Properties

Value: integer

Compatibility: WinIE4+, MacIE4+, Moz1+, Safari1+

The offsetTop and offsetLeft properties are valuable in providing pixel coordinates of an element within the positioning context  of the parent element even when the elements are not positioned explicitly. The element used as a coordinate context for these properties is whatever element the offsetParent property returns. This means that to determine the precise position of any element you may have to add some code that iterates through the offsetParent hierarchy until that property returns null.

Note: The offsetLeft and offsetTop properties for positioned elements in MacIE do not return the same values as the style.left and style.top properties of the same element.


offsetHeight - offsetWidth Properties

Value: integer

Compatibility: WinIE4+, MacIE4+, Moz1+, Safari1+

These properties report the height and width of any element, for a normal block-level element whose height and width are not specified the offsetHeight is determined by the actual height of the content after all text flows. But the offsetWidth always extends the full width of the containing element. For example , a p element consisting of only a few words may report a offsetwidth of many of hundreds of pixels because the p block extends the full width of the body element that represents the containing parent of the p element. To find out the actual width of text within a full-width block-level element wrap the text within an inline element (span) and inspect the offsetWidth property of the span.

Related items: clientHeight, clientWidth properties.


Caching Output

High-traffic sites can often benefit from caching of pages, to save processing of the same data over and over again.

Put the first function cache_start in the beginning of php script and the second cache_end in the end of script.

Code:

function cache_start($_time, $dir)
{
  $cachefile = $dir.'/'.sha1($_SERVER['REQUEST_URI']).'.html';
  $cachetime = $_time;
  ob_start();

  if(file_exists($cachefile) && (time( )-$cachetime < filemtime($cachefile)))
  {
    include($cachefile);
    ob_end_flush();
    exit;
  }
}

//——————————————–

function cache_end($dir)
{
  $cachefile = $dir.'/'.sha1($_SERVER['REQUEST_URI']).'.html';
  $fp = fopen($cachefile, 'w');
  fwrite($fp, ob_get_contents());
  fclose($fp);
  ob_end_flush();
}

//————————————–
$_time : cache time

$dir : directory to cache files


Catching Keywords from Search Engines

With this class we try to catch some keywords from google, yahoo and bing search engines.

Code:

<?php
class keywords
{
 private $referer;
 private $_e;
 public $keywords;

 public function __construct()
 {
   if($_SERVER['HTTP_REFERER'])
   {
     if(preg_match("#\.google|search\.yahoo|\.bing#", $_SERVER['HTTP_REFERER']))
     {
       $this->referer = urldecode($_SERVER['HTTP_REFERER']);
     }
     else
     {
       return;
     }    
   }
   else
   {
     return;
   }    
 }

 private function getSeparators()
 {
   $this->_e = (preg_match("#\?q=|\?p=#", $this->referer)) ? "\?" : "&";
 }

 public function getKeywords()
 {
   if(!empty($this->referer))
   {
     $this->getSeparators();
     //google
     if(preg_match("#\.google#", $this->referer))
     {
       $m_ = preg_match("#{$this->_e}q=(.+?)&#si", $this->referer, $this->keywords);

       if($m_ == 0)
       {
         return false;
       }
     }
     //yahoo
     elseif(preg_match("#search\.yahoo#", $this->referer))
     {
       $m_ = preg_match("#{$this->_e}p=(.+?)\&#si", $this->referer, $this->keywords);

       if($m_ == 0)
       {
         return false;
       }
     }
     //bing
     elseif(preg_match("#\.bing#", $this->referer))
     {
       $m_ = preg_match("#{$this->_e}q=(.+?)\&#si", $this->referer, $this->keywords);

       if($m_ == 0)
       {
         return false;
       }
     }
     else
     {
       return false;
     }

     return $this->keywords[1];
   }
   else
   {
     return false;
   }
  }
}
?>

Save this script as keywords_class.php

Now let’s try to print these keywords.

Code:

<?php
require_once('keywords_class.php');
$keywordsObj = new keywords();
$keys = $keywordsObj->getKeywords();

if($keys)
{
 print $keys;
}
else
{
 print "ooops";
}
?>

Save this code as index.php


nodeValue

Value: number, string, null

Compatibility: WinIE5+, MacIE5+, Moz1+, Safari1+

Of the node types implemented in the W3C DOM - capable browsers, only the text and attribute types have readable values. An element’s node value returns a null value. For an attribute node the nodeValue property consists of the value assigned to that attribute. As an example, nodeValue can be used to increase the width of a textarea object.

function increaseCols(elem)
{
  var colWidth = parseInt(elem.attributes["cols"].nodeValue, 10);
  elem.attributes["cols"].nodeValue = (colWidth * 1.1);
}

As another example you can replace the text of an element:

function replace(elem, newtxt)
{
  if(elem.childNodes.length == 1 && elem.firstChild.nodeType == 3)
  {
    elem.firstChild.nodeValue = newtxt;
  }
}

The function makes one final verification that the element contains one child node and that it is a text type.

Related items: attributes, innerText, nodeType properties.


Drag - Drop Lists

This code uses an open source drag - drop library from Tool-Man to create drag-drop lists. Download and unpack the drag-drop libraries onto your server.

Code:

<html>
 <head>
 <title>Drag - Drop Lists</title>

 <style>
 #cities li {margin:0px;}
 ul.box li {margin:3px;}
 ul.sortable li {position:relative;}
 ul.box
 {
  list-style-type:none;
  padding:0px;
  margin:2px;
  width:20em;
  font-size:13px;
  font-family:"Times New Roman", Times, serif;
 }
 ul.box li
 {
  cursor:move;
  padding:2px 2px;
  border:1px solid #cccccc;
  background:#eee;
 }
 .clickable a
 {
  display:block;
  text-decoration:none;
  cursor:pointer;
  cursor:hand;
 }
 clickable li:hover
 {
  background:#f6f6f6;
 }
 </style>

 <script type="text/javascript" src="source/org/tool-man/core.js"></script>
 <script type="text/javascript" src="source/org/tool-man/events.js"></script>
 <script type="text/javascript" src="source/org/tool-man/css.js"></script>
 <script type="text/javascript" src="source/org/tool-man/drag.js"></script>
 <script type="text/javascript" src="source/org/tool-man/coordinates.js"></script>
 <script type="text/javascript" src="source/org/tool-man/dragsort.js"></script>
 <script type="text/javascript" src="source/org/tool-man/cookies.js"></script> 

 <script type="text/javascript">
 <!--
 var dragsort = ToolMan.dragsort();
 var junkdrawer = ToolMan.junkdrawer();

 window.onLoad = function()
 {
   dragsort.makeListSortable(document.getElementById("cities"), verticalOnly, saveOrder);
 }

 function verticalOnly(item)
 {
   item.toolManDragGroup.verticalOnly();
 }

 function saveOrder(item) { }

 function prepFields()
 {
   document.getElementById("cities_txt").value = junkdrawer.
   serializeList(document.getElementById("cities"));
   return true;
 }
 //-->
 </script>
 </head>
 <body>
 <ul id="cities" class="box">
 <li>Paris</li>
 <li>Rome</li>
 <li>Athens</li>
 </ul>

 <form method="post" action="display.php">
 <input type="hidden" name="cities" value="" id="cities_txt" />
 <input type="submit" onclick="prepFields();" />
 </form>
 </body>
</html>

Save the code as dragdrop.html

The simple code below used to print out values from the list.

Code:

<html>
<body>
You chose: <?=$_POST['states']?>
</body>
</html>

Save the code as display.php.


nodeName Property

Value: string

Compatibility: WinIE5+, MacIE5+, Moz1+, Safari1+

For HTML and XML elements the name of a node is the same as the tag name. The value is an all-uppercase string of the tag name.

Some nodes such as the text content of an element do not have a tag, the nodeName property is a special value: #text.

The following example demonstrates one way to assing a new class name to every p element in an IE5+ document:

function setPClasses(className)
{
  for(var i = 0; i < document.all.length; i++)
  {
    if(document.all[i].nodeName == "P")
    {
      document.all[i].className = "className";
    }
  }
}

Related item: tagName property


nextSibling - previousSibling Properties

Value: Object reference

Compatibility: WinIE5+, MacIE5+, Moz1+, Safari1+

A sibling node is one at the same nested level as another node in the hierarchy of an HTML document. The following p element has tow child nodes (the i and b elements), those tow child nodes are siblings of each other.

<p>Ramones is <i>the</i>  best <b>rock’n'roll</b> band.</p>

The i node has not previousSibling property, the b node has not nextSibling prorerty (return null).

The following example assings the same class name to all child nodes of an element:

function setChildClasses(parentElem, className)
{
  var childElem = parentElem.firstChild;
  while(childElem.nextSibling)
  {
    childElem.className = className;
    childElem = childElem.nextSibling;
  }
}

Related items: firstChild, lastChild, childNodes properties, insertAdjucentElement method.


Magnet Link

This PHP function return the urn (Uniform Resource Name) formed from the content hash of a particular torrent file. The urn refering to the Base32 encoded hash of the file.

Code:

function base32_encode ($hash)
{
$outString = '';
$compBits = '';
$BASE32_TABLE = array(
                         '00000' => 0x61,
                         '00001' => 0x62,
                         '00010' => 0x63,
                         '00011' => 0x64,
                         '00100' => 0x65,
                         '00101' => 0x66,
                         '00110' => 0x67,
                         '00111' => 0x68,
                         '01000' => 0x69,
                         '01001' => 0x6a,
                         '01010' => 0x6b,
                         '01011' => 0x6c,
                         '01100' => 0x6d,
                         '01101' => 0x6e,
                         '01110' => 0x6f,
                         '01111' => 0x70,
                         '10000' => 0x71,
                         '10001' => 0x72,
                         '10010' => 0x73,
                         '10011' => 0x74,
                         '10100' => 0x75,
                         '10101' => 0x76,
                         '10110' => 0x77,
                         '10111' => 0x78,
                         '11000' => 0x79,
                         '11001' => 0x7a,
                         '11010' => 0x32,
                         '11011' => 0x33,
                         '11100' => 0x34,
                         '11101' => 0x35,
                         '11110' => 0x36,
                         '11111' => 0x37,
                         );

   /* Turn the compressed string into a string that represents the bits as 0 and 1. */
   for ($i = 0; $i < strlen($hash); $i++) {
       $compBits .= str_pad(decbin(ord(substr($hash,$i,1))), 8, '0', STR_PAD_LEFT);
   }

   /* Pad the value with enough 0's to make it a multiple of 5 */
   if((strlen($compBits) % 5) != 0) {
       $compBits = str_pad($compBits, strlen($compBits)+(5-(strlen($compBits)%5)), '0', STR_PAD_RIGHT);
   }

   /* Create an array by chunking it every 5 chars */
   $fiveBitsArray = split("\n",rtrim(chunk_split($compBits, 5, "\n")));

   /* Look-up each chunk and add it to $outstring */
   foreach($fiveBitsArray as $fiveBitsString) {
       $outString .= chr($BASE32_TABLE[$fiveBitsString]);
   }
   return $outString;
}

Parametres:

dn - Filename

xl - Size in bytes

xt - urn containing file hash

as - Web link to the file online

xs - P2P link

kt - Key words for search

mt - link to the metafile that contains a list of magneto

xt is the most important part of  magnet links.

Sites that use this kind of magnet links: btscene.com , mininova.org