PROGRAMMING SOLUTIONS

Monday 3 August 2009

Get HTML source using javascript


var source = document.getElementsByTagName('html')[0].innerHTML


Test it!

Javascript prompt


var name = prompt("Whats your name?", "");
if (name != "") {
alert("Welcome " + name);
}



Test it!

Sunday 2 August 2009

Handle cookies in javascript

Here's an object to manipulate cookies, you can set, get or delete a cookie.


function CookieHandler() {

this.setCookie = function (name, value, seconds) {

if (typeof(seconds) != 'undefined') {
var date = new Date();
date.setTime(date.getTime() + (seconds*1000));
var expires = "; expires=" + date.toGMTString();
}
else {
var expires = "";
}

document.cookie = name+"="+value+expires+"; path=/";
}

this.getCookie = function (name) {

name = name + "=";
var carray = document.cookie.split(';');

for(var i=0;i < carray.length;i++) {
var c = carray[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}

return null;
}

this.deleteCookie = function (name) {
this.setCookie(name, "", -1);
}

}

Yes/No message box in javascript

There are many times where we want ask or confirm about an action through a page, this can be achieved using the "confirm" javascript function. The "confirm" function returns 1 if the "OK" button was pressed and 0 for the "Cancel" button.

Example:

function msgboxYesNo() {
if (confirm("Are you sure you want to move to the next page?")) {
window.location.href = "nextpage.html";
}
}


Test it!

How to validate an email address using javascript


function validEmail(email){
var emailReg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailReg.test(email);
}

Drag and drop in javascript

Copy-paste the following code at the top of your html file, inside the head tag.


var DragDropHandler = {


// private property.
_oElem : null,


// Attach drag handler to an element, public function
attach : function(oElem) {
oElem.onmousedown = DragDropHandler._dragBegin;

// callbacks
oElem.dragBegin = new Function();
oElem.drag = new Function();
oElem.dragEnd = new Function();

return oElem;
},


// Begin drag process , private function
_dragBegin : function(e) {
var oElem = DragDropHandler._oElem = this;

if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }

var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);

e = e ? e : window.event;
oElem.mouseX = e.clientX;
oElem.mouseY = e.clientY;

oElem.dragBegin(oElem, x, y);

document.onmousemove = DragDropHandler._drag;
document.onmouseup = DragDropHandler._dragEnd;
return false;
},


// Drag (move) element , private function
_drag : function(e) {
var oElem = DragDropHandler._oElem;

var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);

e = e ? e : window.event;
oElem.style.left = x + (e.clientX - oElem.mouseX) + 'px';
oElem.style.top = y + (e.clientY - oElem.mouseY) + 'px';

oElem.mouseX = e.clientX;
oElem.mouseY = e.clientY;

oElem.drag(oElem, x, y);

return false;
},


// Stop drag process , private function
_dragEnd : function() {
var oElem = DragDropHandler._oElem;

var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);

oElem.dragEnd(oElem, x, y);

document.onmousemove = null;
document.onmouseup = null;
DragDropHandler._oElem = null;
}

}

Saturday 1 August 2009

How to open a popup window using javascript

Pass the following parameters to the OpenPopup fucntion and call it through your javascript code.


url2open = "http://developers-hell.blogspot.com/";
w = 400;
h = 300;
wndName = "Developers-hell";

function OpenPopup(url2open, w, h, wndName) {
mywindow = window.open (url2open, wndName, 'location=1,status=1,scrollbars=1,width='+w+',height='+h+'');
mywindow.moveTo(20,20);
mywindow.focus();
}


Test it!

Trim function in javascript


* " " (ASCII 32 (0x20)), an ordinary space.
* "\t" (ASCII 9 (0x09)), a tab.
* "\n" (ASCII 10 (0x0A)), a new line (line feed).
* "\r" (ASCII 13 (0x0D)), a carriage return.
* "\0" (ASCII 0 (0x00)), the NUL-byte.
* "\x0B" (ASCII 11 (0x0B)), a vertical tab.


function trim(str, chars) {
return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

Tuesday 30 June 2009

A javascript function that returns the item with the max length in an string array

Note that stritems in our case is a single string, containing other strings separated with comas.



function FindMaxItemLength(stritems)
{
var itemsArray=new Array()
itemsArray=stritems.split(",")

var i=0;
var j=0;
var val1='';
var val2='';
var ret_len = 0;

for (i=0;i {
val1=itemsArray[i];
for (j=0;j {
val2=itemsArray[j];
if (val2.length > val1.length)
{
ret_len = val2.length;
}
}
}

return ret_len;
}

A php function that calculates the size of an image to a preview thumb

Note that $equal2Width is by default set to 60 pixels, you can set this parameter to your own needs.


function SetPreviewImageDimensions($img, &$newImgWidth, &$newImgHeight)
{
$equal2Width = 60;

$arrayImg = getimagesize($img);
$ImgWidth = $arrayImg[0];
$ImgHeight = $arrayImg[1];
if ($ImgWidth > $equal2Width) {
$newImgWidth = $equal2Width;
$newImgHeight = ($ImgHeight/$ImgWidth) * $newImgWidth;
}
else {
$newImgWidth = $ImgWidth;
$newImgHeight = $ImgHeight;
}

}

Variables $newImgWidth and $newImgHeight are passed by refference, so the returned values of width and height will be passed in these variables for your later use.

Tuesday 23 June 2009

A simple php function that separates date from time

$d is a date similar to the format yyyy/mm/dd h:m:s , there must be a space between the the date and time part of the given date for the function to work correctly.

If $returnDate is set to true, this function returns the date part
else it returns the time part.

function SeparateDateFromTime($d, $returnDate)
{
$retValue = "";

if ($returnDate==True) { // return date...
$retValue = trim(substr($d, 0, stripos($d, " ")));
}
else { // return time...
$retValue = trim(substr($d, stripos($d, " ")));
}

return $retValue;
}

A simple pagination object in php

Copy and paste the following code to your.php file



class PS_Pagination {
var $php_self;
var $rows_per_page; //Number of records to display per page
var $num_rows; //Total number of rows returned by the query
var $links_per_page; //Number of links to display per page
var $sql;
var $debug = false;
var $conn;
var $page;
var $max_pages;
var $offset;
var $extra_url;

/**
* Constructor
*
* @param resource $connection Mysql connection link
* @param string $sql SQL query to paginate. Example : SELECT * FROM users
* @param integer $rows_per_page Number of records to display per page. Defaults to 10
* @param integer $links_per_page Number of links to display per page. Defaults to 5
*/

function PS_Pagination($connection, $sql, $rows_per_page = 10, $links_per_page = 5, $extra_url) {
$this->conn = $connection;
$this->sql = $sql;
$this->rows_per_page = $rows_per_page;
$this->links_per_page = $links_per_page;
$this->php_self = htmlspecialchars($_SERVER['PHP_SELF']);
$this->extra_url = $extra_url;
if(isset($_GET['page'])) {
$this->page = intval($_GET['page']);
}
}

/**
* Executes the SQL query and initializes internal variables
*
* @access public
* @return resource
*/
function paginate() {
if(!$this->conn) {
if($this->debug) echo "MySQL connection missing
";
return false;
}

if($this->page <= 0) { $this->page = 1;
}

//Calculate Offset
$this->offset = $this->rows_per_page * ($this->page-1);
$this->rows_per_page1=$this->rows_per_page+1;

// check for next page
$rs = @mysql_query($this->sql." LIMIT {$this->offset}, {$this->rows_per_page1}");
# echo $this->sql." LIMIT {$this->offset}, {$this->rows_per_page1}
";

if(!$rs) {
if($this->debug) echo "Pagination query failed. Check your query.
";
return false;
} else {
$this->num_rows = mysql_num_rows($rs);
@mysql_close($rs);
}

//Fetch the required result set
$rs = @mysql_query($this->sql." LIMIT {$this->offset}, {$this->rows_per_page}");
# echo $this->sql." LIMIT {$this->offset}, {$this->rows_per_page}";

if(!$rs) {
if($this->debug) echo "Pagination query failed. Check your query.
";
return false;
}

return $rs;
}

/**
* Display the link to the first page
*
* @access public
* @param string $tag Text string to be displayed as the link. Defaults to 'First'
* @return string
*/
function renderFirst($tag='<<') {
if($this->page == 1) {
return $tag;
}
else {
return ''.$tag.'';
}
}

/**
* Display the link to the last page
*
* @access public
* @param string $tag Text string to be displayed as the link. Defaults to 'Last'
* @return string
*/
function renderLast($tag='>>') {
if($this->page == $this->max_pages) {
return $tag;
}
else {
return ''.$tag.'';
}
}

/**
* Display the next link
*
* @access public
* @param string $tag Text string to be displayed as the link. Defaults to '>>'
* @return string
*/
function renderNext($tag=' >') {
if($this->num_rows > $this->rows_per_page) {
return ''.$tag.'';
}
else {
return $tag;
}
}

/**
* Display the previous link
*
* @access public
* @param string $tag Text string to be displayed as the link. Defaults to '<<' * @return string */ function renderPrev($tag='<') { if($this->page > 1) {
return ''.$tag.'';
}
else {
return $tag;
}
}

/**
* Display the page links
*
* @access public
* @return string
*/
function renderNav() {
for($i=1;$i<=$this->max_pages;$i+=$this->links_per_page) {
if($this->page >= $i) {
$start = $i;
}
}

if($this->max_pages > $this->links_per_page) {
$end = $start+$this->links_per_page;
if($end > $this->max_pages) $end = $this->max_pages+1;
}
else {
$end = $this->max_pages;
}

$links = '';

for( $i=$start ; $i<$end ; $i++) { if($i == $this->page) {
$links .= " $i ";
}
else {
$links .= ' '.$i.' ';
}
}

return $links;
}

/**
* Display full pagination navigation
*
* @access public
* @return string
*/
function renderFullNav() {
return $this->renderFirst().' '.$this->renderPrev().' '.$this->renderNav().' '.$this->renderNext().' '.$this->renderLast();
}

/**
* Set debug mode
*
* @access public
* @param bool $debug Set to TRUE to enable debug messages
* @return void
*/
function setDebug($debug) {
$this->debug = $debug;
}
}
?>





How to init the pagination object in your php code:
// Create a Pagination object
$pager = new PS_Pagination($con, $strSql, $_MAX_ROWS, $_MAX_LINKS, $q_params);
// The paginate() function returns a mysql result set
$pages = $pager->paginate();

Where $con is your connection string,
$strSql is your select statement, example: "select * from employees"
$_MAX_ROWS = max rows per page to show.
$_MAX_LINKS = max links per page to show.
$q_params = other options that you might want to have in your request for having the control of the pages.



Use the following commands to move between the pages

$pager->renderFirst(); // go to the the first page
$pager->renderPrev(); // go to the previous page
$pager->renderNext(); // go to the next page
$pager->renderLast(); // go to the last page

Find your ip address


$serverIP=$_SERVER['REMOTE_ADDR'];
echo $serverIP;

Monday 22 June 2009

php mime_content_type function, checks the file type


if(!function_exists('mime_content_type')) {

function mime_content_type($filename) {

$mime_types = array(

'txt' => 'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',

// images
'png' => 'image/png',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',

// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',

// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',

// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',

// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',

// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
);

$ext = strtolower(array_pop(explode('.',$filename)));
if (array_key_exists($ext, $mime_types)) {
return $mime_types[$ext];
}
elseif (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME);
$mimetype = finfo_file($finfo, $filename);
finfo_close($finfo);
return $mimetype;
}
else {
return 'application/octet-stream';
}
}
}

Monday 27 April 2009

Add JavaScript in blogger (blogspot) post

Summary:
This post talks about why javascript sometimes does not work in blogger post and how to make it works.

Javascript code works well in HTML/Jscript gadgets, so it is no need to talk of this. Here we focus on Javascript in a post.

Let's start with an example. I added this SWFObect Javascript code to embed a flash video player generated by Moyea Web Player (http://www.playerdiy.com/ ) to show videos in my blog post and it was not working:


Player will show here



To my strange is that this code works in my Dreamweaver or other HTML editor. But why does not work in blogger?
I tried many other code and then I found this javascript code work well in blogger post:

Test


After this, I look carefully at my blogger post source (Edit Html):


Player will show here



There is a problem. In almost each new line. Almost Every time you have new line, blogger editor adds
tag. Because of this
tag web browser can't execute jscript.

So correct solution for my problem should look like this:

Player
will show here


To work well javascript in blogger post should be in one line.

Tuesday 27 January 2009

Add A JavaScript Calendar To BloggSpot Blogger


The two most common widgets/gadgets you can see on a blog are clock and calendar. Although you would have seen them in most of the blogs hosted on WordPress, but these are rare in Blogger blogs, as Blogger doesn't directly gives you the facility to add them.

You can see my previous post, on how to embed flash clocks, in your blog here.
And this post, I will help you to add a simple calendar.

You can see the live DEMO here.

And here's the code required to add it to your blog:

Log in to Blogger.com
Go to Layout -> Click on "Add a Gadget" -> HTML/JavaScript type.

And copy paste this code in to it:
<style type="text/css">



.month {

background-color:black;

font:bold 12px verdana;

color:white;

}



.daysofweek {

background-color:gray;


font:bold 12px verdana;

color:white;

}



.days {

font-size: 12px;

font-family:verdana;

color:black;

background-color: lightyellow;


padding: 2px;

}



.days #today{

font-weight: bold;

color: red;

}



</style>






<script type="text/javascript" src="http://dsai.588.googlepages.com/basiccalendar.js">



/***********************************************

* Basic Calendar-By Brian Gosselin at http://scriptasylum.com/bgaudiodr/

* Script featured on Dynamic Drive (http://www.dynamicdrive.com)

* Via http://bloggerstop.net

* This notice must stay intact for use

* Visit http://www.dynamicdrive.com/ for full source code

***********************************************/




</script>

<script type="text/javascript">



var todaydate=new Date()

var curmonth=todaydate.getMonth()+1 //get current month (1-12)

var curyear=todaydate.getFullYear() //get current year



document.write(buildCal(curmonth ,curyear, "main", "month", "daysofweek", "days", 1));

</script>

Save the widget, and your blog will be ready with a new calendar !