Add and Remove items with jQuery

jQuery has been around for a while but only about a year ago I started to use it and understanding how easier life can be when using and implementing solutions with jQuery.
Creating web apps nowadays means creating something the user can control and many times that means letting them create, add and remove something from the interface you conceived.

Today I’m sharing a short and simple tutorial that will teach how to add and remove items from your HTML code using the functions appendTo(); and remove(); from jQuery.
For this particular example I’m not going to be careful creating valid markup although I recommend you to always follow the W3C directives.

Creating the markup

In this example I’m going to create text field and 2 buttons that will allow me to add and remove text fields. Similar to online apps that allow you to create web form.

<a href="#" id="add">Add</a>
<a href="#" id="remove">Remove</a>

<p><input type="text" value="1" /></p>

The <p> around the input is just to add a new line when I add now input’s.


Applying jQuery to the markup


First you need to get jQuery. You can download it from the official jQuery website or use the link from Google Code: http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js


Now you need to call jQuery in the <head> section of you HTML Template using the script tag:


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">&lt/script>

Now you need to add the jQuery under the script you just called:


<script type="text/javascript">

$(function() { // when document has loaded

var i = $('input').size() + 1; // check how many input exists on the document and add 1 for the add command to work

$('a#add').click(function() { // when you click the add link
$('<p><input type="text" value="' + i + '" /></p>').appendTo('body'); // append (add) a new input to the document.
// if you have the input inside a form, change body to form in the appendTo
i++; //after the click i will be i = 3 if you click again i will be i = 4
});

$('a#remove').click(function() { // similar to the previous, when you click remove link
if(i > 1) { // if you have at least 1 input on the form
$('input:last').remove(); //remove the last input
i--; //deduct 1 from i so if i = 3, after i--, i will be i = 2
}
});

$('a.reset').click(function() {
while(i > 2) { // while you have more than 1 input on the page
$('input:last').remove(); // remove inputs
i--;
}
});

});
</script>

Here you have it a simple . You need to keep in mind that every time you refresh the page the items will be gone. You’ll need more codding in order to keep the variables on a database. This is just to cover the basic add / remove functions from jQuery.

Labels:

Compress CSS files using PHP

In order to save your precious bandwidth, you should compress your css files. Doing so is not hard at all using this snippet.

header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {
/* remove comments */
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
/* remove tabs, spaces, newlines, etc. */
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
return $buffer;
}

/* your css files */
include('master.css');
include('typography.css');
include('grid.css');
include('print.css');
include('handheld.css');

ob_end_flush();

Usage


Paste the code in a file named style.php. Don’t forget to include your css files (As seen on line 11 in the example). Once done, open your HTML document and import style.php as you’ll import a css stylesheet:


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

style.php will contain all your css stylesheets, compressed.

Labels:

PHP Date Range by week and by month

Get date range by this week, last week, this month, and last month options by providing offsets.

<?php
function getWeekRange(&$start_date, &$end_date, $offset=0) {
$start_date = '';
$end_date = '';
$week = date('W');
$week = $week - $offset;
$date = date('Y-m-d');

$i = 0;
while(date('W', strtotime("-$i day")) >= $week) {
$start_date = date('Y-m-d', strtotime("-$i day"));
$i++;
}

list($yr, $mo, $da) = explode('-', $start_date);
$end_date = date('Y-m-d', mktime(0, 0, 0, $mo, $da + 6, $yr));
}

function getMonthRange(&$start_date, &$end_date, $offset=0) {
$start_date = '';
$end_date = '';
$date = date('Y-m-d');

list($yr, $mo, $da) = explode('-', $date);
$start_date = date('Y-m-d', mktime(0, 0, 0, $mo - $offset, 1, $yr));

$i = 2;

list($yr, $mo, $da) = explode('-', $start_date);

while(date('d', mktime(0, 0, 0, $mo, $i, $yr)) > 1) {
$end_date = date('Y-m-d', mktime(0, 0, 0, $mo, $i, $yr));
$i++;
}
}

getWeekRange($start, $end);
echo "$start $end";

getMonthRange($start, $end);
echo "$start $end";

?>
Labels:

Simple jQuery Timeout

I needed jQuery to fadeout an item after a certain timeout, and I found it odd that I couldn’t find a native jQuery way to do it.

Whatever. jQuery is so awesome that it doesn’t matter, because here’s what I came up with.

(function($){
$.doAfter = function(time,f) {
$('body').animate({ opacity: 1 }, time, f);
};
})(jQuery);
$(document).ready(function(){
$.doAfter(2500,function() {
$('.fadeout').fadeOut('slow');
});
});
Labels:

Easy payments using Paypal IPN

There are several PHP scripts and classes to process PayPal payments using their native IPN (Internet payment notification) feature. Because the whole process is based on the data you need to send via a web form to the PayPal payment processor these script look very similar.

The payment / notification process is shown via the following graphic:

paypal-graphic

Inside the form there are several required values to process a payment. PayPal gives the advice to post them all to get everything working. The following variables get some special attention:

business = your PayPal email address
cmd = single payments or subscription service (_xclick or _xclick-subscriptions)
return = the URL where the buyer get back after the payment is processed
cancel_return = the URL where the buyer get back if he has cancelled the payment
notify_url = the location where your IPN script is located
rm = how you need the data submitted from PayPal to your IPN script (1=get, 2=post)
currency_code = the currency you accept for your payment
lc = the country version of PayPal where your buyer is send to

There are much more variables, but we think that the other variables (product, order and shipment information) speak for themselves. Find a complete form provided with the example files.

To run some IPN enabled payment process we need a small script which will double check if the data which is send to the IPN script is valid according the data which is stored on the PayPal server. This feature is very important if your e-commerce accepts automatic payments.

The following code is able to check if the payment is valid against the PayPal server. Use this test to decide if the payment is valid or not.

$url = 'https://www.paypal.com/cgi-bin/webscr';
$postdata = '';
foreach($_POST as $i =&gt; $v) {
$postdata .= $i.'='.urlencode($v).'&amp;';
}
$postdata .= 'cmd=_notify-validate';

$web = parse_url($url);
if ($web['scheme'] == 'https') {
$web['port'] = 443;
$ssl = 'ssl://';
} else {
$web['port'] = 80;
$ssl = '';
}
$fp = @fsockopen($ssl.$web['host'], $web['port'], $errnum, $errstr, 30);

if (!$fp) {
echo $errnum.': '.$errstr;
} else {
fputs($fp, "POST ".$web['path']." HTTP/1.1\r\n");
fputs($fp, "Host: ".$web['host']."\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ".strlen($postdata)."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $postdata . "\r\n\r\n");

while(!feof($fp)) {
$info[] = @fgets($fp, 1024);
}
fclose($fp);
$info = implode(',', $info);
if (eregi('VERIFIED', $info)) {
// yes valid, f.e. change payment status
} else {
// invalid, log error or something
}
}

As mentioned before there are some complete solutions available on the internet. If your e-copmmerce site doesn’t have a complex product catalog you should use some static code from the PayPal website. For this guide we checked the PHP toolkit provided by PayPal.


Code condition

The first thing I noticed the code is not very clean and is using a coding style which is based on older PHP versions (f.e. for systems using register globals = On)


Implementation

After some code clean-up it was possible to use the included file together with my shopping cart script. Static variables are defined in one central configuration file and dynamic files are posted via the form in your web application.


IPN features

This script is written to handle the IPN validation process with different methods: cURL, fsockopen, and libcURL. I tried only the fsockopen option because this method looks good to me and should work on almost every web platform.


Documentation

There is a “Readme” file with the information about the most important features. A complete guide is not included and the information about subscription payments is missing in all files and documents. If you decide to start with the original files you should check also the comments within the configuration and example files.

Labels:

Parse html with PHP preg_match_all()

For the most of the PHP developer which are using preg_match or preg_replace frequently is the function preg_match_all a smaller advantage, but for all others it’s maybe hard to understand. The biggest difference between preg_match_all and the regular preg_match is that all matched values are stored inside a multi-dimensional array to store an unlimited number of matches. With the following example I will try to make clear how its possible to store the image paths inside a web page:

$data = file_get_contents("http://www.finalwebsites.com");
$pattern = "/src=[\"']?([^\"']?.*(png|jpg|gif))[\"']?/i";
preg_match_all($pattern, $data, $images);

We take a closer look to the pattern:


"/src=[\"']?([^\"']?.*(png|jpg|gif))[\"']?/i"


The first part and the last part are searching for everything that starts with src and ends with a optional quote or double quote. This could be a long string because the outer rule is very global. Next we check the rule starts within the first bracket:


"/src=[\"']?([^\"']?.*(png|jpg|gif))[\"']?/i"


Now we are looking inside this long string from the outer rule for strings starting with an optional quote or double quote followed by any characters. The last part inside the inner brackets is the magic:


"/src=[\"']?([^\"']?.*(png|jpg|gif))[\"']?/i"


We are looking next for a string that is followed by a file extension and match we get all the paths from the html file.


We need all the rules to isolate the string parts (image paths) from the rest of the html. The result looks like this (access the array $images with these indexes, or just use print_r($images)):


$images[0][0] -> src="/images/english.gif"

$images[1][0] -> /images/english.gif

$images[2][0] -> gif


The index 1 is the information we need, try this example with other part of html code for a better understanding.

Labels:

Create custom backups from your website using cURL

These days I needed a script to backup only a part of a customers website using a CRON. Most of the control panels I know allow only a complete website backup and this is not what I needed. While plaaning the script, I thought about a solution for webmaster without full SSH access to their hosting account. A typical situation could be:

  • A shared hosting account that allows only backups for the whole site incl. database, emails and other settings
  • No administration rights via SSH
  • A FTP host for the storage of the the backup files
  • Support for cURL and a default PHP5 configuration (sorry no more code for PHP4).

First of all we need to create a variable to define the local source directory on your website where you like to start the backup from:

define('BASEPATH', $_SERVER['DOCUMENT_ROOT'].'/');

The next code is to create a new class including the constructor function and some variables used in that class:


class Curl_ftp_backup {

public $basePath, $errors, $ftp_server, $ftp_user_pw , $msg, $email;

public function __construct($ftp_server, $ftp_userpw, $email_adr) {
$this->basePath = BASEPATH;
$this->errors = '';
$this->ftp_server = $ftp_server;
$this->ftp_user_pw = $ftp_userpw;
$this->email = $email_adr;
$this->msg = '';
}
}


Our class will store file and directories on the remote FTP server, the next function will create a directory if it not already exists:



	private function curl_create_ftp_directory($name, $curr_dir = '') {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->ftp_server);
curl_setopt($ch, CURLOPT_USERPWD, $this->ftp_user_pw);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$cmd = array();
if ($curr_dir != '') $cmd[] = 'CWD '.$curr_dir;
$cmd[] = 'MKD '.$name;
curl_setopt($ch, CURLOPT_POSTQUOTE, $cmd);
curl_exec ($ch);
return;
}

The following function will open a file and uploads the data to specified directory on the target server. For each file that is not stored the error number is returned, this information is used later to build up an error string.


	private function curl_put_file($path) {
$ch = curl_init();
$fp = fopen($this->basePath.$path, "r");
curl_setopt($ch, CURLOPT_URL, $this->ftp_server.$path);
curl_setopt($ch, CURLOPT_USERPWD, $this->ftp_user_pw);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($this->basePath.$path));
curl_exec ($ch);
$error = curl_errno($ch);
curl_close ($ch);
if ($error != 0) $this->errors .= $path.PHP_EOL;
return;
}

Now we need a function that will loop through the specified base directory and will switch between directories and files; the previous functions will create the directory or upload the file.


	public function backupfiles($directory) {
if ($handle = opendir($this->basePath.$directory)) {
$this->curl_create_ftp_directory($directory);
while (false !== ($file = readdir($handle))) {
if (is_file($this->basePath.$directory.$file) &amp;&amp; $file != '.htaccess') {
$this->curl_put_file($directory.$file);
} elseif ($file != '.' &amp;&amp; $file != '..' &amp;&amp; is_dir($this->basePath.$directory.$file)) {
$this->backupfiles($directory.$file.'/', $directory);
}
}
closedir($handle);
if ($this->errors != '') {
$this->msg = 'Missing files: '.PHP_EOL.$this->errors;
} else {
$this->msg = 'FTP upload successful.';
}
} else {
$this->msg = 'Can\'t open local directory.';
}
}

public function send_emailmsg() {
if ($this->msg != '') {
$body = PHP_EOL.'Backup result:'.PHP_EOL.PHP_EOL.$this->msg;
mail($this->email, 'Your Backup on '.date('Y-m-d H:i:s'), $body);
}
}

At last there is a tiny function that will send you some short email message about the backup result. You can call the class in your PHP script:


$cb = new Curl_ftp_backup('ftp://ftp.yourserver.com/source_folder/', 'user:password', 'your@email.com');
$cb->backupfiles('includes/');
$cb->send_emailmsg
();

Thats all, now you need to create a CRON job for the file that will execute the backup. If your hosting provider doesn’t provide CRON jobs, just google for “free cron jobs”.


Disclaimer:

We tested the script “successful” on two modern Linux web servers with ~100 files between 10kb and 300MB. If you have a backup with a lot of files you should think about a different solution. With every file or directory a new CURL function is called, this could result in a high server load. We are not responsible for any damage and/or data loss as the result off using this script.

Labels:

FTP Upload via cURL

FTP hosting is often much cheaper than regular web hosting. The upload with an ftp client is for sure the most common way, but could be a problem for people behind a firewall or without enough rights (capabilities) to install a FTP client. For those a upload via a web form is the best solution.

Upload limitations by your web server

The default value for file uploads within PHP is 2MB, if you need to upload bigger files you need to change your PHP configuration or need to create a .htaccess file with this code to upload files of max. 16MB:

php_value upload_max_filesize 16M
php_value post_max_size 20M

The value for the post_max_size is larger than the value for the upload_max_size because we want to be able to upload more than just a file (also other data via text fields or text areas). The .htaccess file needs to be in the same directory than your upload script.


Using cURL for file transmissions

cURL is a great library for file transmissions via different types of protocols. The library supports the transport via POST, GET, FTP upload and much more. cURL is also able to authenticate on the target server or website.


In this tutorial we want to upload a file to some (password protected) remote FTP server via a web form.


<form action="curlupload.php" method="post" enctype="multipart/form-data">
<div>
<label for="upload">Select file</label>
<input name="upload" type="file" />
<input type="submit" name="Submit" value="Upload" />
</div>
</form>

The form is simple and has only one file field and the submit button. Don’t forget to protect this kind of pages.


Next we need some PHP code to handle the upload and opens a stream to send the file via cURL to the remote FTP server (place this code above the html code):


if (isset($_POST['Submit'])) {
if (!empty($_FILES['upload']['name'])) {
$ch = curl_init();
$localfile = $_FILES['upload']['tmp_name'];
$fp = fopen($localfile, 'r');
curl_setopt($ch, CURLOPT_URL, 'ftp://ftp_login:password@ftp.domain.com/'.$_FILES['upload']['name']);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
curl_exec ($ch);
$error_no = curl_errno($ch);
curl_close ($ch);
if ($error_no == 0) {
$error = 'File uploaded succesfully.';
} else {
$error = 'File upload error.';
}
} else {
$error = 'Please select a file.';
}
}

After the user has selected a file, the data is uploaded to the web server. We open the temp file with fopen and the cURL session is initialized. Together with the URL for the remote FTP server, we send the FTP login and password to the target location. The other cURL settings are required to send the file via the FTP protocol to the target server. If the returned error code is equal “0″, the upload was successful.


This small PHP snippet is responsible for the upload to some remote FTP server. We suggest using more validation routines in a production environment.

Labels:

Uploading a file using Curl in PHP

Here's how to upload files using curl in php: (it's very easy)

notice the @ infront of the file path, this is the magic part.

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, _VIRUS_SCAN_URL);
curl_setopt($ch, CURLOPT_POST, true);
// same as <input type="file" name="file_box">
$post = array(
"file_box"=>"@/path/to/myfile.jpg",
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
?>
Labels:

PHP: Random string with numbers and letters

I thought that some of you might find it useful to learn how to generate a random string or a random number with PHP. I wrote a quick function to use PHP to generate random. See it below :

function genRandomString() {
$length = 10;
$characters = ’0123456789abcdefghijklmnopqrstuvwxyz’;
$string = ”;

for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}

return $string;
}
Labels:

Date function parameters for RSS formated date (pubDate)

<?php
$pubDate = date("D, d M o G:i:s T",time());
?>
Labels:

10 jQuery Custom Scrollbar Plugins

jquery-custom-scrollbars

If you ever wanted to add some custom scrollbars to your website, to scroll the contents and the default browser scrollbars just doesn’t match up with your design, than make sure you check this list of 10 jQuery custom scrollbar plugins. Hope you find the following information helpful.

1. jScrollPane – custom cross-browser scrollbars

Kelvin Luck’s jScrollPane was originally developed in December 2006. It is a jQuery plugin which provides you with custom scrollbars which work consistently across all modern browsers. You can style the scrollbars using simple CSS and they degrade gracefully where JavaScript is disabled.

jscrollpane

2. Plugin JQuery : Scrollbar

This page is written in french so use Google’s translate service to translate this page to your preferred language. Download is available for the plugin.
The purpose of this plugin is to add a scrollbar to the item of your choice, to view any content which is larger than the size – vizible space of a div for example. It is aimed to the people who don’t want a default scrollbar. Whell scroll management is also included in this but is not activated.

plugin-jquery-scrollbar

3. Tiny Scrollbar – A lightweight jQuery plugin

Tiny Scrollbar can be used for scrolling content. It was built using the javascript jQuery library. Tiny scrollbar was designed to be a dynamic lightweight utility that gives webdesigners a powerfull way of enhancing a websites user interface. It can scroll vertical or horizontal, supports scrolling by wheel, thumb, or track and the mimified the size is 2,29 kb

tinyscrollbar-jquery

4. jQuery Custom Content Scroller

A custom content scroller created with jquery and css that supports mousewheel, scroll easing and has a fully customizable scrollbar. The script utilizes jQuery UI and Brandon Aaron jquery mousewheel plugin. Very easy to configure and style with css.

jquery-custom-scrollbar

5. jQuery Scrollbar replacements

These scrollbars are fully themable allowing their behaviour to be determined as well as their look. This script uses the ‘jquery.corner’ plugin for the lovely cross-browser rounded corners and ‘jquery.drag’ for more reliable drag event registering.

jQuery Scrollbar replacements

6. Scrollbar Paper

Scrollbar Paper does not replace browser’s default scrollbar.
Instead, it covers it with a custom scrollbar, like paper on a wall: that is why it is called Scrollbar Paper.
The benefit of this approach is that the way browser’s default scrollbar behaves is not modified: mouse wheel support, text selection and scrolling performance are the same as usual.

jQuery Scrollbar Paper

7. A custom scrollbar for a DIV

This tool brings HTML5 range input to all browsers in such a way that you can make it look and behave like you want. This small candy weights only 2.2 Kb. Here the rangeinput is used to control scrolling of a DIV. A little more coding and you can present your products like Apple does.

A custom scrollbar for a DIV jQuery

8. ShortScroll – A jQuery UI Google Wave style scroll bar

Jesse Baird has developed this custom scrollbar as a jQuery UI widget after seeing the scroll bar in Google Wave, which added functionality and style making much better than the browser default scroll bar..CSS3 background gradients to do all of the fancy background stuff so if you plan to support Internet Explorer and care about eye candy, plan on creating your own background images.

ShortScroll - A jQuery UI Google Wave style scroll bar

9. jQuery Scroll

A jQuery plugin which renders a custom, CSS styleable vertical scrollbar.

jQuery Scroll Custom

10. Vertical scrollbar using jQuery UI slider

The code assumes a single div with fixed height (#scroll-pane in my example) which contains an absolutely positioned div (#scroll-content) which contains the content for scrolling.

Vertical scrollbar using jQuery UI slider

[net-kit.com]
Labels: ,

ISAPI Rewrite 3.0 REQUEST_URI work around

Helicon Tech have taken quite a different approach with the release of ISAPI Rewrite 3 in that they have adopted a structure that is very much like mod_rewrite for Apache. ISAPI Rewrite 3 now can read rewrite rules directly from Apache .access files without the user needing to do a thing. Although ISAPI Rewrite 3 is very similar to mod_write for Apache now, there are a few things that do not work the same. Take the REQUEST_URI server variable for instance which doesn't work with IIS as IIS doesn't allow the modification of server variables. What Helicon did here was make their own variable called HTTP_X_REWRITE_URL which does allow the modification of server variables. The only drawback is that this then requires you to replace REQUEST_URI with HTTP_X_REWRITE_URL in all you code, or does it?

Replacing REQUEST_URI with HTTP_X_REWRITE_URL in all your code is certainly one way to do it, but it isn't very practical and also makes your code platform dependent because of ISAPI Rewrite 3. Another way to do it is to use the "auto_prepend_file" directive in php.ini to run some code prior to each script to assign the value of HTTP_X_REWRITE_URL to REQUEST_URI. To do this create a file called "request_uri.php" or similar and enter the following code into it;

<?php
if (isset($_SERVER['HTTP_X_REWRITE_URL']))
{
$_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];
}
?>


Next, open your php.ini file and find the following directive;

auto_prepend_file =


Now set the value to the full path to the php file you just created, for example;


auto_prepend_file = D:\php\request_uri.php


Restart IIS and you should now have the REQUEST_URI variable available to all of your PHP scripts without altering a single line of code which is very handy. For instance the Drupal CMS uses REQUEST_URI when testing for clean URL compatibility, and with the above set Drupal finally passes this test when hosted on IIS.

Labels: ,

Disable Javascript Errors

This simple script will prevent javascript errors from being displayed in your visitor's browser

<script type="text/javascript">
function noError(){return true;}
window.onerror = noError;
</script>

Or jQuery:


$(window).error(function(){
return true;
});

The functionality is very simple: create a function that always returns true, and then whenever an error occurs, call this function (returning true and suppressing the error).


Shamefully, this script is only tested in IE.

Labels: ,

URLLoader Error #2032: Stream Error

This error can be caused by requesting a URL that is over the maximum length supported by Internet Explorer, which is 2083. This can be confusing, because if you copy a URL you are trying to load in Flex with a URLRequest into Internet Explorer, IE will truncate the URL itself, and appear to load properly.

This is especially important for REST API's that can take a long string variable.

The following code will avoid this issue.

var URL_MAX_LENGTH:int = 2083;
var request:URLRequest = new URLRequest(url.substr(0, URL_MAX_LENGTH));

[www.brighthub.com]

Labels:

Detect Window Resize

When I try that - it works fine for me and I get the alert.  I am also using IE6 on WinXP.  My body tag looks like this:

<body onResize="alert('body resize');">

There is another way to do the same thing, and perhaps that method may work for you when this one doesn't for some reason.  Put a script tag in your page like this:


<script language="Javascript">
document.body.onresize = function (){
alert("Thanks for resizing!");
}
</script>

That method also works for me, and it may work for you too.

Labels:

Database Class using PHP

Hi PHP Developers,
I wrote a Database utility class, which is used mostly in any projects. If you've this class, then you don't need to write queries each & every time when a new project comes. You can just copy this file & paste it in your class directory & can call it anytime. The class written below is very simple & it can be understood to the novice also. There will be a way to minimize the functions & statements inside the class too, if so, don't regret to post it in comments.

 

<?php
/*-----------------------------------------------------------------------
Created By: Sathish Kumar.R
Date: 30 July 2010
E-mail: smart2raise[at]gmail[dot]com
Purpose: Database Manipulation


Functions Available:
db: Constructor (for mysql connect)
query: Executing query(mysql_query)
num_rows: Finding total rows(mysql_num_rows)
fetch_object: Fetch results in Object (mysql_fetch_object)
fetch_array: Fetch results in Array (mysql_fetch_array)
fetch_assoc: Fetch results in Array (mysql_fetch_assoc)
insert: Insert query (Insert into...)
insert_id: Gets last inserted ID (mysql_insert_id)
update Update query (Update ...)
delete Delete query (Delete ...)
countof: Count function in mysql
maxof: Max function in mysql
sumof: Sum function in mysql
avgof: AVG function in mysql
last_query: Displays the query which you executed last
throw_error: If any mysql error occurs & you set $debug = true then it will show the query & the mysql error
-------------------------------------------------------------------------*/
class db{
var $debug = false;
var $query = array();
var $prefix = "";
function db($server,$username,$pwd,$db){
mysql_connect($server,$username,$pwd) or die('Please check your database connection');
mysql_select_db($db);
}
function query($qry){
$this->query[] = $qry;
$res = mysql_query($qry);
if(mysql_error()){
$this->throw_error();
}
return $res;
}
function num_rows($res){
return mysql_num_rows($res);
}
function fetch_object($res){
$fet = mysql_fetch_object($res);
return $fet;
}
function fetch_array($res){
$fet = mysql_fetch_array($res);
return $fet;
}
function fetch_assoc($res){
$fet = mysql_fetch_assoc($res);
return $fet;
}
function insert($val,$table){
$query = 'INSERT INTO '.$table.' (';
foreach ($val AS $key => $value)
$query .= '`'.$key.'`,';
$query = rtrim($query, ',').') VALUES (';
foreach ($val AS $key => $value){
if(get_magic_quotes_gpc())
$query .= '\''.$value.'\',';
else
$query .= '\''.mysql_real_escape_string($value).'\',';
}
$query = rtrim($query, ',').')';
return $this->query($query);
}
function insert_id(){
return mysql_insert_id();
}
function update($val,$table,$con){
if($con!=""){
$where = "where ";
$lastitem = end($con);
foreach ($con AS $key => $value){
if($value!=$lastitem){
if(get_magic_quotes_gpc())
$where .= $key."='".$value."' && ";
else
$where .= $key."='".mysql_real_escape_string($value)."' && ";
}
else{
if(get_magic_quotes_gpc())
$where .= $key."='".$value."'";
else
$where .= $key."='".mysql_real_escape_string($value)."'";
}
}
}
else
{
$where = "";
}
$query = 'update '.$table.' set ';
foreach ($val AS $key => $value){
if(get_magic_quotes_gpc())
$query .= $key."=".'\''.$value.'\',';
else
$query .= '\''.mysql_real_escape_string($value).'\',';
}
$query = rtrim($query, ',')." ".$where;
return $this->query($query);
}
function delete($table,$con){
if($con!=""){
$where = "where ";
$lastitem = end($con);
foreach ($con AS $key => $value){
if($value!=$lastitem){
if(get_magic_quotes_gpc())
$where .= $key."='".$value."' && ";
else
$where .= $key."='".mysql_real_escape_string($value)."' && ";
}
else{
if(get_magic_quotes_gpc())
$where .= $key."='".$value."'";
else
$where .= $key."='".mysql_real_escape_string($value)."'";
}
}
}
else {
$where = "";
}
return $this->query("delete from {$table} {$where}");
}
function countof($col,$table,$con="",$group=""){
if($con!=""){
$where = "where ";
$lastitem = end($con);
foreach ($con AS $key => $value){
if($value!=$lastitem){
if(get_magic_quotes_gpc())
$where .= $key."='".$value."' && ";
else
$where .= $key."='".mysql_real_escape_string($value)."' && ";
}
else{
if(get_magic_quotes_gpc())
$where .= $key."='".$value."'";
else
$where .= $key."='".mysql_real_escape_string($value)."'";
}
}
}
else {
$where = "";
}
if($group!="")
$groupby = "group by ".$group;
else
$groupby = "";
$query = $this->query("select count({$col}) from {$table} {$where} {$groupby}");
$fet = $this->fetch_array($query);
return $fet[0];
}
function maxof($col,$table,$con="",$group=""){
if($con!=""){
$where = "where ";
$lastitem = end($con);
foreach ($con AS $key => $value){
if($value!=$lastitem){
if(get_magic_quotes_gpc())
$where .= $key."='".$value."' && ";
else
$where .= $key."='".mysql_real_escape_string($value)."' && ";
}
else{
if(get_magic_quotes_gpc())
$where .= $key."='".$value."'";
else
$where .= $key."='".mysql_real_escape_string($value)."'";
}
}
}
else {
$where = "";
}
if($group!="")
$groupby = "group by ".$group;
else
$groupby = "";
$query = $this->query("select max({$col}) from {$table} {$where} {$groupby}");
$fet = $this->fetch_array($query);
return $fet[0];
}
function sumof($col,$table,$con="",$group=""){
if($con!=""){
$where = "where ";
$lastitem = end($con);
foreach ($con AS $key => $value){
if($value!=$lastitem){
if(get_magic_quotes_gpc())
$where .= $key."='".$value."' && ";
else
$where .= $key."='".mysql_real_escape_string($value)."' && ";
}
else{
if(get_magic_quotes_gpc())
$where .= $key."='".$value."'";
else
$where .= $key."='".mysql_real_escape_string($value)."'";
}
}
}
else {
$where = "";
}
if($group!="")
$groupby = "group by ".$group;
else
$groupby = "";
$query = $this->query("select sum({$col}) from {$table} {$where} {$groupby}");
$fet = $this->fetch_array($query);
return $fet[0];
}
function avgof($col,$table,$con="",$group=""){
if($con!=""){
$where = "where ";
$lastitem = end($con);
foreach ($con AS $key => $value){
if($value!=$lastitem){
if(get_magic_quotes_gpc())
$where .= $key."='".$value."' && ";
else
$where .= $key."='".mysql_real_escape_string($value)."' && ";
}
else{
if(get_magic_quotes_gpc())
$where .= $key."='".$value."'";
else
$where .= $key."='".mysql_real_escape_string($value)."'";
}
}
}
else {
$where = "";
}
if($group!="")
$groupby = "group by ".$group;
else
$groupby = "";
$query = $this->query("select avg({$col}) from {$table} {$where} {$groupby}");
$fet = $this->fetch_array($query);
return $fet[0];
}
function last_query(){
return end($this->query);
}
function throw_error(){
if($this->debug==true){
$qry = "<span style="color: rgb(0, 0, 0);">".end($this->query)."</span>
";
}
else{
$qry = "";
}
die("<div style='width:500px; margin:auto; text-align:left; color:red; font-size:12px;border:2px solid #FFD700;vertical-align:middle; line-height:19px;background:#FFFFDD;font-family:verdana;padding:3px;'>".$qry."Mysql Error: ".mysql_error());
}
}
?>

<?php
//Usage of Class:


$hostname = "hostname";
$username = "username";
$password = "";
$database = "dbname";
$db = new db($hostname,$username,$password,$database);
$db->debug = true;
//If it is set to true, then mysql error will shown the query which throws the error.

$qry = $db->query("select columnname from tablename"); //Executing query
$db->num_rows($qry); //Finding total rows

$val = array("a"=>123,"b"=>"sathish","c"=>"kumar");

$a = $db->insert($val,"tablename");
/*Note: $val should be an array, else it will throw error Key in an array should be the column name in the table & value can be any value */

$db->insert_id(); //returns the last inserted ID in the database

$val1 = array("a"=>123,"b"=>"Sathish","c"=>"Kumar");

$db->update($val1,"tablename",array("id"=>2));
/*
Update query same as insert query, you can pass multiple conditions in the 3rd argument i.e array("id"=>2,"a"=>'123')
*/

$db->delete("tablename",array("id"=>4));
//You can pass multiple conditions in 2nd argument


$db->countof("id","tablename",array("a"=>123123));


$db->maxof("id","tablename",array("a"=>123123));


$db->avgof("id","tablename",array("a"=>123123));

/*
for countof(),maxof(),avgof() you can pass additional argument group by


$db->countof("id","tablename",array("a"=>123123),"c");

this will result as "select count(id) where a = '123123' group by c"
*/

$db->last_query() //This will return last executed query
?>
Labels: ,

Automatic database INSERT/UPDATE class

I built this class because i wanted to have a shortcut for all the times i need to insert or update rows into the database.
The main purpose of this class it to use it when you submit forms.

<?php
/**
* db.class.php
*/
class DB {
/**
* Inserts one item into a table
*
* @param string $table The name of the table
* @param array $items Array of fields to insert (if some is not specified the default value is assumed)
* @return int The new ID of the item
*/
public function insertTableRow($table, $items) {
$this->fixQuotes($items);
$fields = $this->getTableFieldsInfo($table);
$query = "INSERT INTO `$table` (";
foreach ($fields as $info)
$query .= '`'.$info->name.'`, ';
$query = trim($query, ', ');
$query .= ") VALUES(";
foreach ($fields as $info) {
if (isset($items[$info->name])) {
if (strtoupper($items[$info->name]) == "NULL")
$val = "NULL, ";
else
$val = "'".$items[$info->name]."', ";
}
else
$val = "'".$items[$info->def]."', "; //
$query .= $val;
}
$query = trim($query, ', ');
$query .= ")";
//print $query;
$r = mysql_query($query);
return mysql_insert_id();
}
/**
* Updates a table
*
* @param string $table The name of the table
* @param int $id The ID of the row to update
* @param array $items Array of new values ($items['columnName']['value'])
* @return TRUE on success or FALSE on error
*/
public function updateTableRow($table, $id, $items) {
$this->fixQuotes($items);
$fields = $this->getTableFieldsInfo($table);

$query = "UPDATE `$table` SET ";
foreach ($fields as $info) {
if (isset($items[$info->name])) {
if ($items[$info->name] == 'NULL')
$query .= "`".$info->name."` = NULL, ";
else
$query .= "`".$info->name."` = '".$items[$info->name]."', ";
}
}
$query = trim($query, ', ');
$query .= " WHERE ID='$id'";
$r = mysql_query($query);
//print $query;

return $r;
}
//----------------------------------- PROTECTED -----------------------------------//
/**
* Returns an object containing all the fields info of a table
*
* @param strin $table The name of the table
* @return object The fields info as an array of objects like:
* blob: $fieldInfo->blob
* max_length: $fieldInfo->max_length
* multiple_key: $fieldInfo->multiple_key
* name: $fieldInfo->name
* not_null: $fieldInfo->not_null
* numeric: $fieldInfo->numeric
* primary_key: $fieldInfo->primary_key
* table: $fieldInfo->table
* type: $fieldInfo->type
* default: $fieldInfo->def
* unique_key: $fieldInfo->unique_key
* unsigned: $fieldInfo->unsigned
* zerofill: $fieldInfo->zerofill
*/
protected function getTableFieldsInfo($table) {
$query = "SELECT * FROM `$table`";
$result = mysql_query($query);
while ($meta = mysql_fetch_field($result)) {
if ($meta)
$fieldInfo[] = $meta;
}
mysql_free_result($result);
return $fieldInfo;
}
/**
* Fixes single quotes in a string (or array of strings) to store it into the DB without error
* @param mixed $str The string or array of strings to fix (by reference)
*/
protected function fixQuotes(&$str) {
if (is_array($str)) {
foreach ($str as $key=>$text)
$str[$key] = str_replace("'", "''", $text);
}
else
$str = str_replace("'", "''", $str);
}
}
?>

Usage

Let’s see a very practical example to understand how this class can be very useful.


Assume we have a page with a form to submit contact information. First, we need a contact table with these fields:



  • ID

  • first_name

  • middle_name

  • last_name

  • biography


CREATE TABLE `contact` (
`ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`first_name` VARCHAR( 128 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`middle_name` VARCHAR( 128 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`last_name` VARCHAR( 128 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`biography` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL

) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;

Then, we need a file containing the form, for example form.php:


<?php
/**
* form.php
*/
include "db.class.php";
if (isset($_POST['submit'])) {
$DB = new DB();
$DB->insertTableRow('contact', $_POST);
}
else {
echo '
<form action="form.php" method="POST" target="_self">
<p>First Name<br />
<input type="text" name="first_name" value="" /></p>
<p>Middle Name<br />
<input type="text" name="middle_name" value="" /></p>
<p>Last Name<br />
<input type="text" name="last_name" value="" /></p>
<p>Biography<br />
<textarea name="biography"></textarea></p>
<p><input type="submit" value="Submit" /></p>
</form>
';
}
?>

Explanation

The method DB::insertTableRow accepts 2 arguments:



  1. the name of the table

  2. an array of values where the keys must match exactly the name of the columns of the table, and the value can be anything


The nice thing is that:



  1. you don’t have to fill the array with ALL the fields (if you don’t pass a field, the class will automatically detect the default value and store that instead)

  2. the order of the array values doesn’t have to match the order of the fields in the table

  3. the method DB::updateTableRow works the same way:


<?php

//Example 1:

/*
If we want to add another row, this time without a form (the form was only an example to show how easy it is to use the class with forms),
and we know only first name and last name of the person, we just call the method like this:
*/
$DB->insertTableRow ('contact', array ('first_name'=>'Robert', 'last_name'=>'De Niro'));

//---------------------//

//Example 2:
$contact['first_name'] = 'Robert';
$contact['last_name'] = 'De Niro';
$contact['address'] = 'Holliwood';

$DB->insertTableRow ('contact', $contact);

/*
NOTE:
our second example has a field 'address' that doesn't exist in our table!!
It doesn't matter, the class method will only care of those fields that have the same name of one of the columns, and ignore all the others!
*/

//-----------------------------------------------------------------//

//Example 3:
/*
If we want to update the contact table and change the first name of our contact we just need to
pass an array of 1 element where key is the name of the column we want to change and the value is the new name
*/
$DB->updateTableRow ('contact', array('first_name'=>'Peter');

?>
Labels: ,

Javascript to Redirect a Drop Down List (select)

You can redirect using an html select without having to place it in a form, or have the user press a button. The user only needs to change the value.

Check out the following code that you can copy and paste into an html file and take for a test drive:

<html>

<head>
<title>Drop Down List Redirect</title>
</head>

<body>

<select onchange="top.location.href = 'http://www.google.com/search?q='
+ this.options[ this.selectedIndex ].value" >
<option value="">None</option>
<option value="cute+dogs">Cute Dogs</option>
<option value="lasers+beams">Laser Beams</option>
<option value="kitty+cat">Kitty Cat</option>
</select>

</body>
</html>

Breaking down the javascript code into more understandable chunks gives:

// 'this' points to the select object after change the item in the drop down list.
var drop_down = this;

// drop_down.selectedIndex contains the position of the item that was selected from the drop down
var selected_index = drop_down.selectedIndex;

// drop_down.options contains all of html option elements inside the html select
// we need to go to .value to get the 'value="something"' written in the HTML
var selected_value = drop_down.options[ selected_index ].value;

// changing top.location.href redirects ( unless you only append #blah )
top.location.href = 'http://www.google.com/search?q=' + selected_value


I hope you guys find this helpful!



Cheers,

Joseph

Labels: ,

Modify HTTP Headers with PHP

// See related links for more status codes

// Use this header instruction to fix 404 headers
// produced by url rewriting...
header('HTTP/1.1 200 OK');

// Page was not found:
header('HTTP/1.1 404 Not Found');

// Access forbidden:
header('HTTP/1.1 403 Forbidden');

// The page moved permanently should be used for
// all redrictions, because search engines know
// what's going on and can easily update their urls.
header('HTTP/1.1 301 Moved Permanently');

// Server error
header('HTTP/1.1 500 Internal Server Error');

// Redirect to a new location:
header('Location: http://www.example.org/');

// Redriect with a delay:
header('Refresh: 10; url=http://www.example.org/');
print 'You will be redirected in 10 seconds';

// you can also use the HTML syntax:
// <meta http-equiv="refresh" content="10;http://www.example.org/ />

// override X-Powered-By value
header('X-Powered-By: PHP/4.4.0');
header('X-Powered-By: Brain/0.6b');

// content language (en = English)
header('Content-language: en');

// last modified (good for caching)
$time = time() - 60; // or filemtime($fn), etc
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $time).' GMT');

// header for telling the browser that the content
// did not get changed
header('HTTP/1.1 304 Not Modified');

// set content length (good for caching):
header('Content-Length: 1234');

// Headers for an download:
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.zip"');
header('Content-Transfer-Encoding: binary');
// load the file to send:
readfile('example.zip');

// Disable caching of the current document:
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Pragma: no-cache');

// set content type:
header('Content-Type: text/html; charset=iso-8859-1');
header('Content-Type: text/html; charset=utf-8');
header('Content-Type: text/plain'); // plain text file
header('Content-Type: image/jpeg'); // JPG picture
header('Content-Type: application/zip'); // ZIP file
header('Content-Type: application/pdf'); // PDF file
header('Content-Type: audio/mpeg'); // Audio MPEG (MP3,...) file
header('Content-Type: application/x-shockwave-flash'); // Flash animation

// show sign in box
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');
print 'Text that will be displayed if the user hits cancel or ';
print 'enters wrong login data';
Labels:

Fixing mod_rewrite and .htaccess on GoDaddy Hosting

I recently launched a new website on GoDaddy shared hosting. The website required mod_rewrite for SEO-friendly URLs. GoDaddy provides mod_rewrite but every time I tried to hit a two-deep URL, I would get a 404 error. Here's what I had:

# Mod Rewrite
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

The fix to this problem was to add the following directive before my mod_rewrite directives:


#Fix Rewrite
Options –Multiviews

Tada! The URLs began working and the website's SEO has taken off!


[credit: davidwalsh.name]

Labels:

Easy Jquery Auto Image Rotator

The other week I had a friend ask me for a simple script to rotate a few images on his web page. Sounded simple and I even assumed I would not have to re-invent the wheel, but after an hour of searching for a lightweight script I was surprised to find that unless you were willing to install rather large plug-ins along with jquery there were not allot of options for the simple rotation of images except out-dated scripts. So I decided to come up with my own image rotator that uses jquery's already built in effects.

Jquery Image Rotator Functionality Checklist.

What we need our Jquery image rotator to do:

  1. Rotate Images with Links.
  2. Valid XHTML.
  3. Lightweight Script.
The Rotator as I have come to call it will simply auto rotate through a list of images with a smooth fade effect without the need to include an extra plug-in on top of Jquery.

Let's look at the XHTML, CSS, and Jquery Javascript that makes it work.

Jquery Image Rotator, View Demo, Download Source.

The HTML for our jquery image rotator gets placed in the body of your page.

<div id="rotator">
<ul>
<li class="show">
<a href="javascript:void(0)">
<img src="images/image-1.jpg" width="500" height="313" alt="pic1" />
</a>
</li>
<li>
<a href="javascript:void(0)">
<img src="images/image-2.jpg" width="500" height="313" alt="pic2" />
</a>
</li>
<li>
<a href="javascript:void(0)">
<img src="images/image-3.jpg" width="500" height="313" alt="pic3" />
</a>
</li>
<li>
<a href="javascript:void(0)">
<img src="images/image-4.jpg" width="500" height="313" alt="pic4" />
</a>
</li>
</ul>
</div>

The CSS


/* rotator in-page placement */
div#rotator {
position:relative;
height:345px;
margin-left: 15px;
}
/* rotator css */
div#rotator ul li {
float:left;
position:absolute;
list-style: none;
}
/* rotator image style */
div#rotator ul li img {
border:1px solid #ccc;
padding: 4px;
background: #FFF;
}
div#rotator ul li.show {
z-index:500;
}

The JavaScript


Include jquery and the below script in your page or in an attached file.



<script type="text/javascript">

function theRotator() {
//Set the opacity of all images to 0
$('div#rotator ul li').css({opacity: 0.0});

//Get the first image and display it (gets set to full opacity)
$('div#rotator ul li:first').css({opacity: 1.0});

//Call the rotator function to run the slideshow, 6000 = change to next image after 6 seconds
setInterval('rotate()',6000);

}

function rotate() {
//Get the first image
var current = ($('div#rotator ul li.show')? $('div#rotator ul li.show') : $('div#rotator ul li:first'));

//Get next image, when it reaches the end, rotate it back to the first image
var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div#rotator ul li:first') :current.next()) : $('div#rotator ul li:first'));

//Set the fade in effect for the next image, the show class has higher z-index
next.css({opacity: 0.0})
.addClass('show')
.animate({opacity: 1.0}, 1000);

//Hide the current image
current.animate({opacity: 0.0}, 1000)
.removeClass('show');

};

$(document).ready(function() {
//Load the slideshow
theRotator();
});

</script>

To activate jquery image rotator place the above code in your page head or an attached file. You can adjust the time before the next image appears by altering the setInterval value as well as the fade time itself by changing the animate duration


[alohatechsupport.net]

Labels:

jQuery Fubar – How To Create A Website Toolbar From Scratch And Add Widgets To It

fubars

Over the past year, we’ve seen website toolbar’s become an increasingly popular way for site-owners to offer users a consistent set of powerful social features, regardless of what page they’re on – Share, Subscribe, Tweet, Talk – you name it and chances are there’s a toolbar out there that offers some variation of these features. Facebook were one of the first companies to introduce this toolbar concept and have been the source of inspiration for many others.

Taking a leaf from their book, companies like Wibiya and Meebo have been at the forefront of a toolbar-for-the masses revolution, offering easily customizable widgets for almost anyone to install on their pages. Larger companies have also been hopping onto the toolbar-band too, with sites like CNET.com embracing this concept as a way to offer their visitors more ways to interact with their site.

In today’s post, I’m going to show you how to create your very own jQuery-powered website toolbar and then we’re going to pack it full of lots of useful widget features such as those found in the Wibiya-toolbar – I call it jQuery Fubar.

What Site-bars Are Out There At The Moment?

As I mentioned, we’ve all seen the widget-packed Wibiya Toolbar in action and they’ve recently moved from their invite-only model to being fully open to the public. Meebo (the popular web destination for online IM services) also started offering their own version of this toolbar and both of them offer something a little different (Meebo for example includes a pretty funky drag-and-share feature). Today, we’ve going to create our very own awesome website toolbar, but from a design perspective here’s how the Meebo and Wibiya bars look close-up.

Wibiya

image

Meebo

image

Now that we know what we’re aiming for, let’s see how easy it can be to put together something like this ourselves.

fubar_part1

The First Step – Fixed Positioning with CSS

The first step in creating a website-toolbar is creating an empty div which can be correctly fixed-positioned at the bottom of any webpage. The HTML for this is:

<div id="content">&nbsp;</div>

<div id="floatingbar"><ul> <li><a href="#">Item name</a></li> <br /><li><a href="#">Item name</a></li> <br /><li><a href="#">Item name</a></li> <br /><li><a href="#">Item name</a></li> <br /></ul></div>


and the CSS for this can be found below.



  div#floatingbar
{
overflow: hidden;
width: 100%;
height: 0px;
position: absolute;
bottom: 0;
left: 0;
}

@media screen
{
body&gt;div#floatingbar
{
position: fixed;
}
}


Whilst fixed-positioning isn’t very difficult to achieve using browsers like FireFox and Chrome, it’s been notoriously buggy to code for Internet Explorer 6. Thankfully TagSoup came up with this wonderful set of CSS/JS hackswhich claim to support fixed-positioning all the way back to IE5. If you’re creating a toolbar from scratch, I would definitely recommend reading their post as it’ll save you a lot of time later on. The IE Fix for this is:



JavaScript/HTML:



<link rel="stylesheet" type="text/css" href="css/fixed4ie.css" />
<script type="text/javascript">onload = function() {
content.focus() }
</script>


CSS:



body
{
height: 100%;
overflow: hidden;
font-size: 100%;
}
div#content
{
width: 100%;
height: 100%;
overflow: auto;
}


Once you’ve got your basic-toolbar in place…



The next thing you’re going to want to do is begin adding in some basic styling around it. Most website-toolbars are around the same dimension in height (although there is no official “standard”) so I’m going to set the height of my component as well as some very basic skinning and CSS to style my list items. The background design is made possible with a blue gradient PNG that has some light shadows added to it – similar to the kind of design Wibiya have gone for. Although CSS3 could be just as equally used to create this effect, remember that some people still use IE!



div#floatingbar
{
overflow: hidden;
width: 100%;
height: 38px;
position: absolute;
bottom: 0;
left: 0;
color: #000;
font-family:Arial;
font-weight:bold;
background-image:url('../images/tui.png');
}

#floatingbar ul {
list-style-type:none;
}
#floatingbar ul li
{
float:left; padding:14px;
color:#666; margin-top:-3px;
}
#floatingbar ul li a
{
text-decoration:none;
color:#fff; padding: 10px;
font-size:12px; font-weight:normal;
font-family:Arial;
}
#floatingbar ul li a:hover { color:#000033;}


Now that this is done, I also want to add some basic animation to my toolbar so that when users first load up their page, the bar will slide up from the bottom. This is made possible using jQuery’s great animate() feature by keeping the initial height of the component at 0 and then tweening it up to it’s maximum height over a period of time. The code for this can be found below



CSS:



div#floatingbar
{
height: 0px;
}


JavaScript:



<script type='text/javascript'> 
$(function() {
$('#floatingbar').css({height: 0}).animate({ height: '38' }, 'slow');
});
</script>


This will end up creating something a little like this



Next, populate the toolbar with some links and some more jQuery Magic





In the next step of development, we’re going to add some nice visual effects to the toolbar, with the assistance of two of my favorite jQuery plugins – the first will provide us with some lightweight tooltips for our toolbar items whilst the second is going to be used for displaying our content.



1. jQuery Tipsy Tooltips for Toolbar Elements – This is a plugin used for adding Facebook-Like Tooltip effects to your site or links (http://onehackoranother.com/projects/jquery/tipsy/)



Sample Usage:



<script type='text/javascript'> 
$(function() {

$('.toolbarLink').tipsy({gravity: 's'});

});
</script>


2. jQuery PrettyPhoto - This is a lightbox alternative that allows you to display any type of content, in particular, iFrame content from local or external websites (http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/)



Sample Usage:



<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$(".gallery a[rel^='prettyPhoto']").prettyPhoto({theme:'facebook'});
});
</script>


Let’s start adding some social features to the toolbar



addingos





When I first looked at the Wibiya toolbar, the big features that appealed to me were how easy it made it for any user to interact with all of the social networks associated with a website. I could easily take a look at the site’s Twitter account or become a fan of their Facebook Fan page, I could even easily browse through all their pictures without having to leave the page I was on. That "ease" of access impressed me, so I developed my website toolbar with widgets in mind.



When there are so many different ways currently available to pull in your recent tweets or display your Flickr albums in an easily scrollable box, why not find an implementation you like and just customize it?. So, that’s what we’re going to do.



1. Google Buzz Plugin – Mike More’s excellent Google Buzz Widget grabs the feed of your latest Google Buzz posts and refreshes this list depending on a set of parameters you’ve configured (http://www.moretechtips.net/2010/02/google-buzz-widget-jquery-plugin.html)



2. Sea of Clouds jQuery Twitter Plugin – This wonderfully compact plugin makes pulling your Twitter feeds a piece of cake and also allows you to customize the output quite extensively (http://tweet.seaofclouds.com/)



3. Facebook Fan Page Widget - The Facebook Fan Page Widget is a widget provided free by Facebook to site owners wishing to share their fan streams or followers in a box on their website. To allow you to show to Fan Box widgets side by side as in the original Wibiya bar, one can either choose to proxy one of the content boxes or load each of the widgets in separate iFrames which are then loaded into the same window.



4. Coolris Express Viewer - CoolIris offer the public a free version of their commercial 3D-Wall Component for use on your own personal sites. They’ve got a fantastic widget generator online that lets you pull in feeds from all sorts of sources including Flickr, YouTube or your own RSS Feed. It then takes this information and renders it as a scrollable wall of thumbnails that’s easy to view.



5. AddToAny Subscription and Share Widgets – These excellent widgets allow you to configure everything down to the event handlers that execute them so you can choose whether they appear on click or on mouse over. All the usual share sites and social networks are included and these guys even offer an API to anyone wishing to do more with their code.



6. ConveyThis.com Translation Features – Google Translate has been a favorite service among many of my fellow coders for a while now, but I came across this great service that allows you to give your visitors the choice to pick what translation service they want to use to translate your page once they’ve selected a language. Because some services have stronger features in one area of language than others, your visitors will have all the options they could want available to them. ConveyThis? also has a great widget you can add easily to your site, so definitely check it out.



Widget Delivery




Widgets (or plugins such as a Twitter-Reader or Translation service) can be delivered to our visitors through the site-bar in two main methods. The first is on page-load and the second is dynamically on-demand. The second of these options is the most beneficial as it means that we only have to load up the plugin when a user requests it. This can be either done through Ajax-Calls or iFrames.



In my implementation I have opted for iFrames through the PrettyPhoto Light-Box plugin – I thought this was a good idea because it provides a nice sandboxed area where the widget can execute as required without the chance of it interfering with the other widgets on the page. Whilst this isn’t a problem for most modern browsers, sandboxing widgets into iFrames can help lower the bug rate for older browsers like IE6.



To host a widget inside a lightbox iFrame, all you need to do is write or paste the code for it, once configured, into a new html file, save it into a local file in your toolbar directory and call it via PrettyPhoto as follows:



<a rel="prettyPhoto[iframe]" href="widget.html" title="Here's the tooltip text " class="toolbarLink"> My Page</a>


You can then freely call any widget file, with it’s very own themes if desired the same way you would any other link used from a lightbox. prettyPhoto also includes some pagination by default so if you want to easily flick through all of the widgets available on your toolbar you can do so through the controls at the bottom of the lightbox.



Further Customization & Demos



It’s possible to further customize your toolbar by adding in icons next to each of your widget links and floating them accordingly. For the example in today’s post, I’ve used some fantastic 24×24 icons from iconfinder.net, and you can see the final version of this page here (or click below to expand the screenshot).



image



You can also take your imagination one step further and replace all of the text in your toolbar with some nice images – I personally spent a few minutes putting together some gradient text in PhotoShop and here’s what the final product looked like.



image



With a little more work you could easily add some nice toggle buttons to the side of the toolbar to allow visitors to open or close it and there are a lot more widgets out there that you could experiment adding to your version.



and that’s it!. If you found today’s tutorial helpful, let me know in the comments section below.



Download All Of Todays Examples



You can download all of today’s examples including both the CSS/Icons version of Fubar as well as the Graphics version from the link below. All widgets can be obtained or generated from the site’s referenced in the list earlier in the article, but I’m also including my own ones in the example pack so you can see how easy it is to get setup.



dlbutton



Bonus: Fixed-Position Website Toolbar Plugins



As a bonus to today’s post, I’m also sharing some of the best out-of-the-box alternative solutions and tutorials available for creating your own customized fixed-position Site Bar. We all know that Wibiya is great for a one-click solution, but if you need something a little different one of these will definitely be able to help if the tutorial above doesn’t give you what you’re after.



CSS3 Fixed-Position Toolbar for your site with Social Networking Icons



image



Learn how to create a fantastic fixed footer toolbar for your site – this version includes some usefully placed social networking and subscription icons, great eye-candy tooltip effects and a complete tutorial on how to create it from start to finish. CSS3 Effects compliment it further with some nice visual design touches. Recommended for those who aren’t looking for extensive changes in customization to the above design and currently have more of a functionality requirement.



Facebook Style Footer-Toolbar from Soh Tanaka



image



Soh Tanaka presents this excellent tutorial on how to create a Facebook Style Fixed Site Footer toolbar. This implementation is very close to how the real Facebook site-bar looks and feels and even includes a follow-up tutorial on how to create a pop-out Friends List Chat bar. Recommended for those looking for a fully-featured example of how to create a floating site toolbar for further customization.



Floating Footer Toolbar



image



This entry from Ben Nadel, the most barebones of my recommended tutorials for today, will show you how to build a very very simple implementation of a floating site toolbar. This doesn’t include any of the sample icons or buttons that Soh Tanaka’s version above does so if you want an example that you can literally just start adding your own content to, this would be the one to get.  Ben’s version has been tested with many browsers including IE6, so cross browser compatibility won’t be an issue!.



JixedBar – A Fixed-Position Toolbar plugin for jQuery



image



Here’s a recently updated plugin that takes a lot out of the effort out of creating a fixed-position toolbar for your site. All you need to do is create a <ul> /<li> structure for each split section and then have the plugin transform it into the toolbar for you. It’s a hassle-free way of adding this feature to your projects and at under 7KB, it’s definitely a recommended download.



[addyosmani.com]

Labels:

12 Great jQuery Plugins to Fully Control Styling of Your HTML Form Elements

newtitle23

HTML Forms are essential for inviting visitors on a site to provide input, giving information about themselves, sharing opinions and so on. The information will on most cases be very valuable for the owner of the web site why making the forms more accessible and better drawing visitors attention is a key objective.  This post provides a list of jQuery plugins that makes it simple and allows you to cake full control of the look and feel of your HTML forms.

WooThemes - Made by Designers

Uniform

Introducing Uniform, a plugin for jQuery that lets you style select, radio, and checkboxes however you desire.

jqueryforms

prettyCheckboxes

This script is for people who wants to have a consistent look for checkboxes across browser or those who simply want them to look better. By using this script you wont loose any of the regular inputs usability.

jqueryforms

How to create Skype-like buttons using jQuery

If you use Skype I am sure that you noticed that animated button for adding more people to a chat. When you click on it the icon on the left “jumps” for a few times. I love that animation. And that’s why I’m going to show you how to create the same button using jQuery and some simple CSS.

jqueryforms

Justify Elements Using jQuery and CSS – Tutorial

When creating a web form you have to make a functional and visually aligned layout. The simplest way to do this is to place elements in a table or by fixing the width of labels. But what if you don’t want to use tables and you want to align input elements according to the width of the longest label? This small jQuery tutorial shows you how.

jqueryforms

Highlight

Highlight increases usability by highlighting elements as you interact with the page. Its primary use is for forms, but it can also be used for tables, lists, or any element you specify.

jqueryforms

Custom Checkbox with jQuery

This script provides you with the ability to customize the design of checkboxes in your web forms. You can use the default skin and the Safari skin which are provided with the package.

jqueryforms

jqTransform

This plugin is a jQuery styling plugin wich allows you to skin form elements.

javascript-frameworks

jquery.Combobox

An unobtrusive way of creating a HTML type combobox from a existing HTML Select element(s), a Demo is here.

jqueryforms

Make image buttons a part of input fields

If you ever saw how products like Microsoft CRM look like you probably noticed there are input fields that have “embedded” image buttons inside them. If your clients saw that, there is a probability that they will want to have it in their applications.

Whether you agree or not, here is how you can do it easily. So easily that you will have to add just a few lines of code and enable this feature in entire application.

jqueryforms

Radio Button and Check Box Replacement

How to replace radio buttons and check boxes with jQuery.

jqueryforms

mcDropdown

mcDropdown allow users to select from a complex hierarchical tree of options.

jquery-form-enhancements
Geogoer VChecks

Avery user friendly way to show checkboxes.

javascript-frameworks

[tripwiremagazine.com]
Labels: ,

Simple jQuery Zebra Stripe Table with Row Hover and Highlight class

Was just trying to build a fully functional table or grid by using jQuery. I see there are many tutorials with Zebra Stripe Tables by using  jQuery. Here I am trying to make Simple jQuery Zebra Stripe Table with Row Hover Class and Row Highlight Class or Row Selected Class.

jquery_table_rows_hover_selected_colors

The CSS used for this example is as below:

body{
font-family:Arial, Helvetica, sans-serif;
}
table.tablecolors{
border-collapse:collapse;
width: 728px;
border: 2px solid #940103;
}
table.tablecolors td{
padding: 8px 6px;
font-size: 12px;
border: 1px solid #FFF;
}
table.tablecolors .even{
background-color: #efefef;
}
table.tablecolors .odd{
background-color: #FFF;
}
table.tablecolors .hovcolor{
background-color: #4f8c00;
color:#FFF;
cursor:pointer;
}
table.tablecolors .highlightcolor{
background-color: #8c2800;
color:#FFF;
}


 



The simple jQuery script or code snippet:



$(document).ready(function() {
$("table.tablecolors tr:even").addClass("even");
$("table.tablecolors tr:odd").addClass("odd"); //This is not required - you can avoid this if you have a table background
$("table.tablecolors tr").hover(function(){
$(this).addClass("hovcolor");
}, function(){
$(this).removeClass("hovcolor");
});
$("table.tablecolors tr").click(function(){
//$("table.tablecolors tr").removeClass("highlightcolor"); // Remove this line if you dont want to de-highlight the previously highlighted row
$(this).toggleClass("highlightcolor");
});
});


 



If you see the above script, you can avoid either “even” or “odd” class and its jQuery declaration if you place a table background color – but it is required when you want to have different font or different image background or borders etc.



In the same way if you don’t want to highlight the previous selected row once the another row is clicked, means like if you want to have only one row selected at a time, then you can un-comment the following line – if not leave it as is.



 



$("table.tablecolors tr").removeClass("highlightcolor");


 



And I don’t think there is any other simple method to achieve this via jQuery? – if so please share the code.



Check the final example and let me know if you are looking out for any further enhancements to be done to the table and its functionality. I can give  you one suggestion which I have in mind – like having a header and footer for the tables by using jQuery?



If you have any suggestions to improve please drop me a message – I will look into it.

Labels:
2010 WEBSITE20. All rights reserved.