How to use JavaScript to detect mobile and hand held devices

If you are maintaining separate web pages on your website for visitors viewing your website on their mobile phones or hand held devies then you can use the following JavaScript code to check the visitor’s user agent and direct them to the relevant web pages.

<script type="text/javascript">

var mobile = function(){
return {
detect:function(){
var uagent = navigator.userAgent.toLowerCase();
var list = this.mobiles;
var ismobile = false;
for(var d=0;d<list.length;d+=1){
if(uagent.indexOf(list[d])!=-1){
ismobile = true;
}
}
return ismobile;
},
mobiles:[
"midp","240x320","blackberry","netfront","nokia","panasonic",
"portalmmm","sharp","sie-","sonyericsson","symbian",
"windows ce","benq","mda","mot-","opera mini",
"philips","pocket pc","sagem","samsung","sda",
"sgh-","vodafone","xda","palm","iphone",
"ipod","android"
]
};
}();

if(mobile.detect()){
// Direct the visitor to the mobile version of your website
}

else{
// Direct the visitor to the desktop version of your website
}

</script>

If you look closely at the code above you can add more user agents with passage of time so your website is up to date with up and coming mobile phones and hand held devices.

Please note if the visitor has disabled JavaScript then the above code will not work.

Let me know if you have any questions/comments

How to use CKEditor in your web page using JavaScript

CKEditor has replaced its older version FCKEditor with more features and enhanced browser compatibility with latest versions of Firefox and Chrome. It’s also more secure than FCKEditor which has been exploited by hackers several times in the past.

Use the following JavaScript code to instantiate CKEditor on a web page

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">if (typeof jQuery == 'undefined') google.load("jquery", "1");</script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript"><!--
$(document).ready(function() {
$('textarea').each(function() {
CKEDITOR.replace($(this).attr('name'),
{
coreStyles_underline : { element : 'u' },
width : 760,
language: 'en'
});
});
});
//--></script>

Add the above code in the <head> section of your web page. The code assumes that you have copied the CKEditor folder where the web page resides. If the CKEditor resides in another folder then please make changes to the path in the above code snippet.

Comments?

How to implement Lightbox effect in Zencart

Lightbox effect is now the defacto standard for displaying product, category and other images on your website. Javascript popups are a thing of the past and really don’t look that cool. As more and more website content management and e-commerce frameworks provide this feature I will today discuss how we can use this in Zencart.

Zencart provides a very easy to install module known as the “Zen Lightbox” which you can download from the Free Software Add Ons section.

After downloading the module you can run the install.sql and copy the files from the images, classes, functions and languages (do change the folder name to your template where necessary) to your Zencart folder as they are all new files and do not overwrite any existing file. You will need to be more cautious for the files in the modules and templates folders as they will overwrite your existing files.

In my case I just needed to display the lightbox effect for the images on the product detail page so I made the following customizations in the tpl_product_info_display.php file.

1. First I placed a check to make sure whether Zen Lightbox was enabled or not. If it was then I include the necessary files.

<?php
if (ZEN_LIGHTBOX_STATUS == 'true') {
  require_once(DIR_FS_CATALOG . DIR_WS_CLASSES . 'zen_lightbox/slimbox.php');
  require_once(DIR_FS_CATALOG . DIR_WS_CLASSES . 'zen_lightbox/autoload_default.php');		
}
?>

2. Then I check whether the image on which the lightbox effect is to be applied is an individual image or part of a gallery.

<?php
if (ZEN_LIGHTBOX_GALLERY_MODE == 'true' && ZEN_LIGHTBOX_GALLERY_MAIN_IMAGE == 'true') {
	$rel = 'lightbox-g';     //in case of image to be part of gallery
} 
else {
        $rel = 'lightbox';       //in case of individual image
}
?>

3. Finally I call the zen_lightbox function which generates the necessary code for the lightbox to take effect.

<a href="<?php echo zen_lightbox('path to product image', 'product name', width, height); ?>" rel="<?php echo $rel; ?>"><img src='path to product image' alt='product name' width='width' height='height'/></a>

Looking above at the 3 steps you can see how easy it is to implement lightbox effect in Zencart. If you would like to view a live example then please click here.

How to validate only digits and decimal points in Javascript?

Our company had implemented an online payment form where customers could pay online on the company website against outstanding invoices or any other service. However, the validation on the form regarding the payment amount field was pretty simple as it was just checking whether the customer had input amount in the field or not and not whether the format of the data was correct or not. For e.g. the customer could have just entered some alphabets and the validation would not have been able to pick it.

Even though this problem would not have caused any major problem and the payment mechanism later on would have caught it, the issue still had to be resolved as it was bad in terms of user friendliness. I coded a function which would check for illegal values and point them out to the user.

function numFilter(input) {
s = input.value;
filteredValues = "1234567890.";
var numValid = 0;
for (i = 0; i < s.length; i++) {  
	var c = s.charAt(i);
	if (filteredValues.indexOf(c) == -1) {} else { numValid++ };
}
if (numValid == s.length) 
        return true;
else
	return false;	
}

The above function checks whether the input values in the text box are numbers and decimal point and alerts if a character other than the above is used. The function could also be used on the onkeypress event of the input box with slight modifications.

Hope the above helped.

How to customize the style drop down in FCKEditor

One of my clients wanted to use the same CSS classes which were being used on the public website in the FCKEditor so that he could apply the classes in one go while writing the content.
Now the Style drop down is populated through the fckstyles.xml in FCKEditor directory root. Its basically an XML file where you can instruct FCKEditor to generate which tag and apply which style to that tag. Below is an excerpt of the XML present in that file

<Styles>
<Style name=”Custom Bold” element=”span”>
<Attribute name=”style” value=”font-weight: bold;” />
</Style>
</Styles>

You can set the name of the class in the name attribute. The HTML tag to generate in the element attribute. Define the style in the attribute tag by writing the actual style formatting in the value attribute.
Define the number of classes you wish to define here, save the file and refresh the page. You will now see all the styles you have defined in the fckstyles.xml

Hope the above helps

Disable Enter key on form

If you need to disable JavaScript on your form then apply the following code in the <head> tag.

<!–
<script language=”javascript” type=”text/javascript”>
function checkEnterkey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
if (evt.keyCode == 13) { return false; }
}
document.onkeypress = checkEnterkey;
</script>
–>

How to use AJAX to check user already exists or not in PHP

AJAX is a wonderful technology that provides the visitor with a “no refresh” experience on the web. With the advent and popularity of Web 2.0 this technology is making progress by leaps and bounds.

If you would like to verify whether a user is registered on your website or not then you can use the following code to implement that functionality.

As AJAX uses JavaScript we will be using the XMLHTTP object.

<script><!--
/*
Due to browser compatibility issues following function instantiates the right object with respect to the browser
*/

function getHTTPObject() {
var xmlhttp;

if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}

// Instantiating the object
var http = getHTTPObject();
// --></script>

Next we will define the function which actually gets called to verify the user from the web page

<script><!--
function getMemberEmail() {
/*
Place validation code here to verify whether the input is in the correct format or not.  If it is not in the correct format then prompt user other wise start checking the user.
*/

sId = document.frmCheck.txtEmail.value;
document.getElementById('spnMessage').innerHTML = "Please wait...";
var url = "chk_user_email.php?e=";

// Note the http is a global variable as you can see from the above code

http.open("GET", url + escape(sId), true);
http.onreadystatechange = handleResponse;
http.send(null);
}
// --></script>

Now we have to write the code which handles the response from the chk_user_email.php file.

<script><!--

function handleResponse() {
/*
We have to check the response status and whether the operation has completed or  not. 4 means completed and 200 means that response is OK.
*/

if (http.readyState == 4) {
if(http.status==200) {
var results=http.responseText;
document.getElementById('spnMessage').innerHTML = results;
}
}
}
// --></script>

The complete code as it would appear on the page for the above example is below:

<script><!--
function getHTTPObject() {
var xmlhttp;

if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}

var http = getHTTPObject();

function getMemberEmail() {

sId = document.frmCheck.txtEmail.value;
document.getElementById('spnMessage').innerHTML = "Please wait...";
var url = "chk_user_email.php?e=";

http.open("GET", url + escape(sId), true);
http.onreadystatechange = handleResponse;
http.send(null);
}

function handleResponse() {

if (http.readyState == 4) {
if(http.status==200) {
var results=http.responseText;
document.getElementById('spnMessage').innerHTML = results;
}
}
}
// --></script>
<form> <input name="txtEmail" type="text" />
<span id="spnMessage" type="text" /> </span>

</form>

Check for whitespace in Javascript

If  you have ever come across form validation in HTML then you will have come across the issue of visitors inputting white space in the form controls and submitting it which does not serve any purpose to the client. Not only that this could also be seen as a potential vulnerability by spammers.

So the best way to go about this is to place validation to check for white space and what better way than to use regular expression for checking it.

You can use the following function to check for white space:

function chkspace(str)
{
isWhiteSpace = new RegExp(/^\s+$/);
if (isWhiteSpace.test(str)) {
return false;
}
return true;
}