Browse: JavaScript

Small, Lightweight and Unobtrusive Scripts, Tools

retrieve-yahoo-weather
In this tutorial I will show you how to display the Yahoo! Weather on your website, using a PHP RSS Parser, called Magpie RSS and JQuery (AJAX). The Weather RSS Feed uses 2 parameters: ‘p’ for location & ‘u’ for degree units. The base URL for the Weather RSS Feed is http://weather.yahooapis.com/forecastrss. An address that gets the weather forecast in Sunnyvale, CA (zip code: 94089) in Celsius (c) looks like this: http://weather.yahooapis.com/forecastrss?p=94089&u=c.
Read more from this entry…

Did you notice how many sites have a verification tool for the ‘username’ field when you try to register? Many use the power of AJAX to check if the nickname has already been assigned to an existing member. This short tutorial gives you an idea of how you can make such a feature in the pages of your website. We’ll use JavaScript (JQuery) and PHP.

Let’s start creating the page where the visitor will type the “username”:

index.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE>An AJAX Username Verification Tool</TITLE>
  <META NAME="Keywords" CONTENT="form, username, checker">

  <META NAME="Description" CONTENT="An AJAX Username Verification Script">

<script type="text/javascript" src="jquery-1.2.6.min.js"></script>

<link rel="stylesheet" type="text/css" href="style.css" />

As you can see the JQuery library and the CSS file (will reveal its contents later) are included. Now let’s continue creating the script that takes the input value and sends it to check.php in order to determine if the username is already in use or not. I will explain you the code in detail below.

<SCRIPT type="text/javascript">
<!--
/*
Credits: Bit Repository
Source: http://www.bitrepository.com/web-programming/ajax/username-checker.html
*/

pic1 = new Image(16, 16);
pic1.src="loader.gif";

$(document).ready(function(){

$("#username").change(function() { 

var usr = $("#username").val();

if(usr.length >= 4)
{
$("#status").html('<img src="loader.gif" align="absmiddle">&nbsp;Checking availability...');

    $.ajax({
    type: "POST",
    url: "check.php",
    data: "username="+ usr,
    success: function(msg){  

   $("#status").ajaxComplete(function(event, request, settings){ 

	if(msg == 'OK')
	{
        $("#username").removeClass('object_error'); // if necessary
		$("#username").addClass("object_ok");
		$(this).html('&nbsp;<img src="tick.gif" align="absmiddle">');
	}
	else
	{
		$("#username").removeClass('object_ok'); // if necessary
		$("#username").addClass("object_error");
		$(this).html(msg);
	}  

   });

 } 

  }); 

}
else
	{
	$("#status").html('<font color="red">' +
'The username should have at least <strong>4</strong> characters.</font>');
	$("#username").removeClass('object_ok'); // if necessary
	$("#username").addClass("object_error");
	}

});

});

//-->

</SCRIPT>

Read more from this entry…

Basic JS Function to Show/Hide (Toggle) an Element

Posted on November 12, 2008, Filled under JavaScript,  Bookmark it

This is a simple JS function to show/hide an element. The element is hided by setting its ‘display’ CSS attribute to none. When the element is showed back the ‘display’ attribute is set to block.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE>A Basic Show/Hide JavaScript Function</TITLE>
  <META NAME="Author" CONTENT="Bit Repository">

  <META NAME="Keywords" CONTENT="show, hide, js, function">
  <META NAME="Description" CONTENT="A Basic Show/Hide JavaScript Function">

<STYLE TYPE="text/css">

<!--
#info_box {
border: 1px solid green;
padding: 3px;
margin-top: 10px;
-moz-border-radius: 3px;
display: none;
}
-->
</STYLE>

<SCRIPT LANGUAGE="JavaScript">
<!--
function toggle(name)
{
var id = document.getElementById(name);

  if(id.style.display == '') // Invisible? Show it
  {
  id.style.display = 'block';
  }
  else if(id.style.display == 'block') // Visible? Hide it
  {
  id.style.display = '';
  }
}
//-->
</SCRIPT>

 </HEAD>

 <BODY>

Click <a href="JavaScript: toggle('info_box');">here</a> to show/hide the info box.

<div id="info_box">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Curabitur at leo. Quisque tempus.</div>

 </BODY>
</HTML>

DEMO

Basic Usage of the JS onChange() Event Handler

Posted on November 11, 2008, Filled under JavaScript,  Bookmark it

The onChange() event handler is used when the value of an input or select field is changed and based on that change an event is triggered: a form validator, a URL redirection based on the selected value from the dropdown etc. Below I will show you some usage examples of this JavaScript event:

Trigger a form validator (real time)

This is a sample contact form with a JS validator for: name, email & message:

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> onChange() Event Handler (Form Validator)</TITLE>
  <META NAME="Author" CONTENT="Bit Repository">

  <META NAME="Keywords" CONTENT="onchange(), form validation, select, redirect">
  <META NAME="Description" CONTENT="Some basic usage examples of onChange();">

<!-- Preload Images (validated & error icons) -->

<SCRIPT language="JavaScript">
<!--
pic1 = new Image(16, 16);
pic1.src="images/icon_tick.gif";

pic2 = new Image(16, 16);
pic2.src="images/icon_error.gif";
//-->
</SCRIPT>

<SCRIPT LANGUAGE="JavaScript">
<!--
function checkField(field)
{
var okay = '<img src="images/icon_tick.gif" align="absmiddle">';

var icon_error = '<img src="images/icon_error.gif" align="absmiddle">';

// NAME

if(field.id == 'name')
{
	if(field.value.length < 2)
	{
	var str = icon_error + '&nbsp;<font color="red">Error! The name should have at least 2 characters.</font>';
	}
	else
	{
	var str = okay;
	}
}

// E-MAIL

if(field.id == 'email')
{
// http://javascript.about.com/library/blre.htm

emailRe = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2,10})$/

	if (!emailRe.test(field.value))
	{
	var str = icon_error + '&nbsp;<font color="red">Error! You should enter a valid e-mail address.</font>';
	}
	else
	{
	var str = okay;
	}
}

// MESSAGE

if(field.id == 'message')
{
	if(field.value.length < 20)
	{
	var str = icon_error + '&nbsp;<font color="red">Error! The message should have at least 20 characters.</font>';
	}
	else
	{
	var str = okay;
	}
}

document.getElementById(field.id + "_status").innerHTML = str;

return false;
}
//-->

</SCRIPT>

 </HEAD>

 <BODY>

<form name="form" action="javascript:alert('success!');">
  <table width="804" border="0">

    <tr>
      <td width="324">Full Name:<br />
        <INPUT id="name" size="43" type="text" name="name" onChange="JavaScript: checkField(document.form.name);"></td>

      <td width="470"><div id="name_status"></div></td>
      </tr>
    <tr>
      <td>E-Mail:<br />

	  <INPUT size="43" type="text" id="email" name="email" onChange="JavaScript: checkField(document.form.email);"></td>

      <td valign='bottom'><div id="email_status"></div></td>
    </tr>

	<tr>
      <td>Subject (optional):<br />

	  <INPUT size="43" type="text" id="subject" name="subject"></td>
      <td valign='bottom'>&nbsp;</td>

    </tr>

	<tr>
      <td>Message:<br />
	  <TEXTAREA ID="message" NAME="message" ROWS="8" COLS="33" onChange="JavaScript: checkField(document.form.message);"></TEXTAREA></td>

      <td valign='top'><div style="margin-top: 20px;" id="message_status"></div></td>
    </tr>

	<tr>

      <td><input type="submit" name="submit" value="Submit"></td>
    </tr>

	</table>

</form>
 </BODY>
</HTML>



Redirect to URL upon selection

The follow script redirects a visitor based on what he selected from the dropdown:

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> onChange() Event Handler (URL redirector upon select)</TITLE>
  <META NAME="Author" CONTENT="Bit Repository">

  <META NAME="Keywords" CONTENT="onchange(), redirector, on select">
  <META NAME="Description" CONTENT="Some basic usage examples of onChange();">

<SCRIPT LANGUAGE="JavaScript">

<!--
function redirect(url)
{
window.location = url;

var status = "<br /><font color='green'>Loading " + url +"...</font>";

document.getElementById("loading_status").innerHTML = status;
}
//-->
</SCRIPT>

 </HEAD>

 <BODY onLoad="document.getElementById('loading_status').innerHTML = '';">

<form name="form" action="javascript:alert('success!');">

Select a website:
<select name="website" onChange="JavaScript: redirect(document.form.website.options[document.form.website.selectedIndex].value);">

<option value="http://www.yahoo.com/">Yahoo</option>
<option value="http://www.msn.com/">MSN</option>
<option value="http://www.cnn.com/">CNN</option>
<option value="http://www.google.com/">Google</option>

</select>

<div id="loading_status"></div>

</form>
 </BODY>
</HTML>


I was googling for a way to show a drop down menu with states that populates another menu with counties from the selected state. I found a nice dynamic dependent drop down script (with categories & subcategories) at dreamwebstore.com. However, adding over 2000 counties in a single JavaScript file is not such a good idea because such a script is quite big (200KB+) and in many cases (a slow internet connection, some downloads in progress etc.) it will take some time to load.

I’ve decided to keep the counties from each state in separate files. For instance, if we select Hawaii state (with 5 counties), only the hi.js file will load which has only a size of 515 bytes. To do this I’ve used the powerful JavaScript library JQuery.

Dependent DropDown Select Element

Read more from this entry…

Equivalent of PHP’s array_combine() function

Posted on October 15, 2008, Filled under JavaScript,  Bookmark it

This is a JavaScript function that works like array_combine() in PHP. Below you have the function and a usage example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE>Equivalent of PHP's array_combine() | JavaScript Library</TITLE>
  <META NAME="Author" CONTENT="Bit Repository">

  <META NAME="Keywords" CONTENT="array_combine, php, javascript">
  <META NAME="Description" CONTENT="Equivalent of PHP's array_combine() | JavaScript Library">

<SCRIPT LANGUAGE="JavaScript">

var first_array = new Array('green', 'red', 'yellow');

var second_array = new Array('avocado', 'apple', 'banana');

/*
// Alternative way of creating the arrays

var first_array = new Array();

first_array[0] = "green";
first_array[1] = "red";
first_array[2] = "yellow";

var second_array = new Array();

second_array[0] = "avocado";
second_array[1] = "apple";
second_array[2] = "banana";

*/

/*
Parameters: a - array of keys to be used, b - array of values to be used

IMPORTANT: The number of elements for each array must be equal
*/

function array_combine(a, b)
{
    if(a.length != b.length)
	{
		return false;
	}
	else
	{
		new_array = new Array();

		for (i = 0; i < a.length; i++)
        {
           new_array[a[i]] = b[i];
	    }

		return new_array;
    }
}

var combined_array = array_combine(first_array, second_array);

// Let's print the array in PHP's style

document.write("Array<br>{<br>");

for (key in combined_array)
{
document.write("[" + key  + "] => " + combined_array[key] + "<br>");
}

document.write("}<br>");

</SCRIPT>

</HEAD>
<BODY>
</BODY>
</HTML>

The output will be like the one resulted from the print_r() function in PHP:

echo "<pre>"; print_r($combined_array); echo "</pre>";
Array
{
[green] => avocado
[red] => apple
[yellow] => banana
}

Equivalent of PHP’s in_array() function

Posted on September 13, 2008, Filled under JavaScript,  Bookmark it

Hello coders,

This is a JavaScript function that works like in_array() in PHP. Below is the function with a usage example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE>Equivalent of PHP in_array() | JavaScript Library</TITLE>
  <META NAME="Author" CONTENT="Bit Repository">

  <META NAME="Keywords" CONTENT="in_array, php, javascript">
  <META NAME="Description" CONTENT="Equivalent of PHP in_array() | JavaScript Library">

<SCRIPT LANGUAGE="JavaScript">

function in_array(string, array)
{
   for (i = 0; i < array.length; i++)
   {
      if(array[i] == string)
      {
         return true;
      }
   }
return false;
}

var extensions = new Array("jpg","jpeg","gif","png","bmp");

/*
// Alternative way of creating the array

var extensions = new Array();

extensions[1] = "jpg";
extensions[0] = "jpeg";
extensions[2] = "gif";
extensions[3] = "png";
extensions[4] = "bmp";
*/

var str_to_check = "bmp";

if(in_array(str_to_check, extensions))
{
  alert(str_to_check +" is in our array.");
}
else
{
  alert(str_to_check +" is not in our array.");
}

</SCRIPT>

</HEAD>
<BODY>
</BODY>
</HTML>

If you have any comments or suggestions regarding this script please post them.

Validating an image upload

Posted on September 8, 2008, Filled under JavaScript,  Bookmark it

This is a useful JavaScript function which validates an image upload by checking the extension of the file that should be uploaded. If the extension is jpg, jpeg, png or gif it will return true. Otherwise, it will return false.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE>Validate image on upload @ BitRepository.com</TITLE>
  <META NAME="Author" CONTENT="Bit Repository">

  <META NAME="Keywords" CONTENT="validate, extensions, file, javascript">
  <META NAME="Description" CONTENT="A JavaScript Extension Validator for Images">

<SCRIPT LANGUAGE="JavaScript">

<!--
function validate()
{
var extensions = new Array("jpg","jpeg","gif","png","bmp");

/*
// Alternative way to create the array

var extensions = new Array();

extensions[1] = "jpg";
extensions[0] = "jpeg";
extensions[2] = "gif";
extensions[3] = "png";
extensions[4] = "bmp";
*/

var image_file = document.form.image_file.value;

var image_length = document.form.image_file.value.length;

var pos = image_file.lastIndexOf('.') + 1;

var ext = image_file.substring(pos, image_length);

var final_ext = ext.toLowerCase();

for (i = 0; i < extensions.length; i++)
{
    if(extensions[i] == final_ext)
    {
    return true;
    }
}

alert("You must upload an image file with one of the following extensions: "+ extensions.join(', ') +".");
return false;
}
 //-->

 </SCRIPT>

 </HEAD>

<BODY>

<center>

<form name="form" action="http://www.microsoft.com" enctype="multipart/form-data" method="post" onSubmit="return validate();">

<h2>Validate image on upload</h2>

<br />

	Upload an image: <INPUT type="file" name="image_file"> <input type="submit" name="submit" value="Submit">

</form>

</center>

</BODY>

</HTML>

NOTE: You can add more extensions to the validator by continuing the extensions array.

Good luck!


AJAX Form with CAPTCHA, Realtime Validation and PHP Backend

Create any type of Anti-Spam Forms with AJAX Form Builder

Posted on September 2, 2008, Filled under AJAX, jQuery, PHP,  Bookmark it

This is a professional multi-usage AJAX Form Builder meant to enhance the functionality of your website by providing an interactive user experience for your readers that need to reach you, whether they need to send a feedback, share their opinion regarding your website, fill a survey, leave a testimonial or even make a room reservation online.

Beside the premium AJAX Form, I would like to offer you a short tutorial regarding the creation of a basic AJAX Contact Form. It will give you an idea of how you can create similar web applications using jQuery and AJAX.

The aim of the tutorial is to help you to create a simple (tableless) ajax contact form using AJAX, JQuery & PHP. We will have a HTML page which will contain the form, a CSS file, a php page where the data will be sent and another file where the validation function(s) will be located. JQuery is a new and powerful library which simplifies the way that you write JavaScript.

Step 1 – Creating the configuration file

config.php

<?php
// To
define("WEBMASTER_EMAIL", 'your_name@domain.com');
?>

Here you should fill the e-mail address where you wish to receive the mail as well as the address where you wish to receive the replies (usually the same).

Step 2 – Creating the css file

style.css

/*
Credits: Bit Repository
CSS Library: http://www.bitrepository.com/
*/

html, body  { padding: 0; border: 0px none; }

.notification_error
{
border: 1px solid #A25965;
height: auto;
width: 90%;
padding: 4px;
background: #F8F0F1;
text-align: left;
-moz-border-radius: 5px;
}

.notification_ok
{
border: 1px #567397 solid;
height: auto;
width: 90%
padding: 8px;
background: #f5f9fd;
text-align: center;
-moz-border-radius: 5px;
}

.info_fieldset { -moz-border-radius: 7px; border: 1px #dddddd solid; }

.info_fieldset legend
{
border: 1px #dddddd solid;
color: black; 

font: 13px Verdana;

padding: 2px 5px 2px 5px;
-moz-border-radius: 3px;
}

.button
{
border: 1px solid #999999;
border-top-color: #CCCCCC;
border-left-color: #CCCCCC; 

background: white;

color: #333333; 

font: 11px Verdana, Helvetica, Arial, sans-serif;

-moz-border-radius: 3px;
}

/* Label */
label {width: 140px; padding-left: 20px; margin: 5px; float: left; text-align: left;}

/* Input, Textarea */
input, textarea
{
margin: 5px;
padding: 0px;
float: left;

border: 1px solid #999999;
border-top-color: #CCCCCC;
border-left-color: #CCCCCC; 

color: #333333; 

font: 11px Verdana, Helvetica, Arial, sans-serif;

-moz-border-radius: 3px;
}

/* BR */

br { clear: left; }

Read more from this entry…