replace target=_blank of anchor tag using javascrpt for w3c strict document type

JavaScript 8 Comments »

If you are using strict mode as your html document type and if you have target=_blank in your html code then wc3 gives you an error. strict mode does not accept target=_blank and they suggest to use transitional mode.

here is the javascript replacement for target=_blank. before this you have to set the rel attribute of anchor tags to “external” or anything you wish because this is used in the javascript code so see which are all the anchor tags has set the rel attribute to external .

in other words you can set the rel attribute with some value to mean that these are the tags which has to be opened in a new window.

<script type="text/javascript">
 
function target_blank()
{
 
     var anchors = document.getElementsByTagName("a");
     for (var i=0; i<anchors.length; i++) 
     {
          if ((anchors[i].href!='') && anchors[i].rel == "external")
               anchors[i].target = "_blank";
     }
}
 
window.onload = target_blank;
 
</script>

here is a script with which you can make a single anchor tag open in new window using javascript

<a href="some.html" 
onclick="window.open(this.href); return false;" 
onkeypress="window.open(this.href); return false;">
Open in new window using javascript</a>

stop loading windows messenger when outlook starts

Windows Tips No Comments »

To remove windows messenger from loading when outlook 6 starts follow these steps.

start – run – in the box type gpedit.msc.
A window will appear

in that select
local computer policy – Administrative Templates – windows components – Windows Messenger
In the right pane you will have two options and you can double click them and choose enable.

Start outlook. go to tools – general and disable messenger option from auto logging if present.

this is for windows messenger and not for msn messenger.

static variables in javascript

JavaScript 5 Comments »

static variables in javascript

In javascript functions and objects work in the same manner. Functions are also objects.
so a function can have a member variable like in objects.
A member variable will retain its value between function calls.
So this aspect is used for having a static variable in javascript.
Actually there is no option like static variables in javascript. so here the member variable server as a static variable in javascript.

here is one simple script which uses a static variable to maintain a counter

<script>
function addmore()
{
	if(!addmore.counter)addmore.counter = 0;
	addmore.counter++;
	alert(addmore.counter)
}
 
addmore();
addmore();
 
</script>

or here is another version

<script>
function addmore()
{
	if(!this.counter)this.counter = 0;
	this.counter++;
	alert(this.counter)
}
 
addmore();
addmore();
 
</script>

i have used this for multiple file uploads where there will be an addmore button and a variable to maintain the count of number of uploads to display and once this.counter is greater than 10 then i alert a message that uploads cannot be more than 10.

some people had an idea that why done we use like the following instead of using it like a member function

<script>
var counter=0
function addmore()
{
	counter++;
	alert(counter);
}
addmore();
addmore();
 
</script>

my answer is not to mess up the code with too many declarations which uses the word var…
after a long time we would wonder which variable is for which function
and if the variable is with respect to the context of the process then that will a good practice of maintaing standards and more meaningful.

if you would like to suggest an alternate please comment on this because i would like to know more if there is anything beyond my scope on this.

replace width and height of html element using regular expression

PHP 8 Comments »

php code to replace the width and height of any html tag using php and regular expression.

i had a youtube listing for the admin where i display 10 per page but usually the object tag width and height will be around 400×350 approximately.
but i want to show the youtube video small in the admin section so that it will match the size of each row which will have edit, delete buttons…
here i wished the width and height to be around 100×80.

so when i display the youtube object tag code from the data base i used the following regular expression to replace the original width and height with my preferred value.

and here is the code to do the width and height replacement. it works for me and hope for you too…

$pattern = "/height=\"[0-9]*\"/";
$string = preg_replace($pattern, "height='120'", $rs['url']);
$pattern = "/width=\"[0-9]*\"/";
$string = preg_replace($pattern, "width='200'", $string);
echo $string;

we have another alternate for the above …

you can write the above code in one line by using alternation

 
$pattern = '/(width|height)="[0-9]*"/i';
//

you can use single-quotes instead of double-quotes to reduce the need to escape characters like double-quotes and backslashes.

the input was like this…

<object width="425" height="344">
<param name="movie" value="http://www.youtube.com/v/GwQMnpUsj8I&hl=en&fs=1">
</param><param name="allowFullScreen" value="true">
</param><param name="allowscriptaccess" value="always">
</param><embed src=http://www.youtube.com/v/GwQMnpUsj8I&hl=en&fs=1 
type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344">
</embed></object>

and the output will be like this…

<object width="200" height="120">
<param name="movie" value="http://www.youtube.com/v/GwQMnpUsj8I&hl=en&fs=1">
</param><param name="allowFullScreen" value="true">
</param><param name="allowscriptaccess" value="always">
</param><embed src=http://www.youtube.com/v/GwQMnpUsj8I&hl=en&fs=1 
type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="200" height="120">
</embed></object>

there are two width and height attributes which got replaced… one is in the first line and next is for the embed tab inside.

dirname() and __FILE__ to find parent and current folder of a path or php script

PHP No Comments »

__FILE__ is a magic constant along with __LINE__ and some more which i have not yet used.

dirname() is a function which returns the directory name of a path.

as we combine these two we get something interesting… at least for me.

my problem was to find the current directory of the executing php script. i was not comfortable using dirname($_SERVER[‘PHP_SELF’]) because i got only the folder name and not the complete path…

and then i was gazing the pages online to find what could be the alternat… then it is all this __FILE__ and dirname functions which gives the complete parent folder path which i was in need of many times.

to get current director’s full abs path we can use the following
dirname(__FILE__)
and the parent directory full abs path we can use the following
dirname(dirname(__FILE__))
and it can go further…

$dir = str_replace ( “\”,/, dirname ( _FILE_ ) )
// for Windows based systems

another use of __FILE__ is for debugging purpose while using queries.

i have many queries executed for a page and if there was an error at any point then i have to waste time to find at which place it is unless you append some text like this to find the location (mysql_error().”while this query”)…

so i tried using similar to this to get the line number of the error occured.

mysql_query($query) or showError('status.php',mysql_error(),__LINE__,__FILE__);

if an error occured i will set the error in a session in the showError function and then i will redirect to a status page where it displays the error, line number and the filename where the error occured. and then clear the err string session to make it ready for the next error status…

the following urls are good resources for dirname and __FILE__
php.net manual for function dirname

PHP Magic Constants

access your gmail mails using php imap

PHP IMAP 2 Comments »

Accessing your google mail using php IMAP feature. The php IMAP functions does a lot of interesting work. the following code is written for gmail. This code connects to the gmail imap service through SSL which is listening on port 993. others servers listen to port 143 by default.

The return value is used with other functions to get the desired result.
here it is imap_listmailbox and imap_headers function.

imap_listmailbox will list all the mail boxes with respect to the mail server like inbox, sent, deleted etc..

imap_headers will list all the head of ever message that is the subject of each message in an default order. you can use the iteration index to open a specific message body to read the content of a mail.

so, for now … here we go…

<?php
$conx = imap_open("{imap.gmail.com:993/imap/ssl}", "yourid@gmail.com", "yourpassword");
 
echo "<h1>Mailboxes</h1>\n";
$folders = imap_listmailbox($conx, "{imap.gmail.com:993}", "*");
 
if ($folders == false) {
    echo "Call failed<br />\n";
} else {
    foreach ($folders as $val) {
        echo $val."<br />";
    }
}
 
echo "<h1>Headers in INBOX</h1>\n";
$headers = imap_headers($conx);
 
if ($headers == false) {
    echo "Call failed<br />\n";
} else {
    foreach ($headers as $val) {
        echo $val . "<br />\n";
    }
}
 
imap_close($conx);
?>

find absolute position of an html element

JavaScript 3 Comments »

Html elements are displayed cascading by default. So every element appears one after the other and it is the same with nested elements. I mean elements within another element.

I want to find the exact absolute position of an element. In other words i want to find the exact x,y of an element in the html page if you could consider the html page as a graph.

I used left and top but it will always give the x and y with respect to the parent and not to the window or the body tag which is the first parent for all visible elements. Then i read about the property offsetLeft and offsetTop but this too is with respect to the parent.

So find the parents left + its parent left + its parent till you reach the top then you will get the left of any element. The same way for finding the top that is y. here is the function which will give you the x,y/absolute position of any element.

But when i used float left property i found this function returned a different value so please check when using float left option. anyway …

function findAbsolutePosition(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
//returns an array
}


and to my surprise i found the following link when i tried to find something like this to check my work.

http://www.quirksmode.org/js/findpos.html

I use this site to cross check my snippets in javascript if present. This is one useful site i have found which analyses beyond the scope.

SERVER variable of DOCUMENT_ROOT in windows hosting

PHP No Comments »

One of my projects was uploaded to a windows hosting and i found server of document root was not working. So i searched and i found the following gimmick of using it in windows hosting.

<?php
if ( ! isset($_SERVER['DOCUMENT_ROOT'] ) )
  $_SERVER['DOCUMENT_ROOT'] = str_replace( '\\', '/', substr(
    $_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF']) ) );
?>

show javascript date in words

JavaScript No Comments »
function showDateInWords(dt)
{
 
var dys = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday')
var mns = new Array('Jaunary','February','March','April','May','June','July','August','September', 'October','November','December')
 
var sam = dt.split('-');
var day,month,year
day = sam[0]; month=sam[1]; year=sam[2];
var nd = new Date()
nd.setYear(year);
nd.setMonth(month-1);
nd.setDate(day);
 
	var dt = nd.getDay()	
	var fin = dys[dt]
 
	var daynumber = nd.getDate()
 
	if(daynumber==10 && daynumber==19)
		daynumber =  daynumber + 'th' 
	else if( (daynumber % 10) == 1)
			daynumber =  daynumber + 'st' 
	else if( (daynumber % 10) == 2)
			daynumber =  daynumber + 'nd' 
	else if( (daynumber % 10) == 3)
			daynumber =  daynumber + 'rd' 
	else
			daynumber = daynumber + 'th' 
 
	fin = fin + ', '+ daynumber + ' '+mns[nd.getMonth()+1]  +' '+ sam[2] 
 
	return fin;
}
 
alert(showDateInWords('1-6-2009'))

find age using javascript

JavaScript No Comments »
 
 
<script language="javascript">
 
function Age()
{
var bday=parseInt(document.forms[0].txtBday.value);
var bmo=(parseInt(document.forms[0].txtBmo.value)-1);
var byr=parseInt(document.forms[0].txtByr.value);
var byr;
var age;
var now = new Date();
tday=now.getDate();
tmo=(now.getMonth());
tyr=(now.getFullYear());
 
{
if((tmo > bmo)||(tmo==bmo & tday>=bday))
{age=byr}
 
else
{age=byr+1}
alert("As of today, "+now+' \n'+", you are:"+(tyr-age)+ " years old");
}}
 
</script>

here is the form

 
<form><center>
Enter your birthday&nbsp;&nbsp;<input type="text" name="txtBday" size="2"><br/>
Enter your birth Month(1-12)<input type="text" name="txtBmo"size="2"><br/>
Enter your 4 digit birth year<input type="text" name="txtByr"size="4" ><br/>
<input type="button" value="submit" onClick="alert('er');Age()">
<br/><input type="reset" value="reset"></center>
</form>
Entries RSS