The Infinite Loop – Beginner's SEO, Beginner C# & JQuery Tutorials Problem. Problem Solved. Loop. – The life of a programmer

29May/104

Paging in PHP – PHP Paging Tutorial

PHP Paging & Automatic Pagination Tutorial - Paging made easy

I have written a php paging tutorial before. Admittedly, it wasn't the greatest. I don't think I was as clear as I wanted to be. SO I'm trying again. :) At the end of this tutorial, there is a file named php-automatic-pagination.php.txt
Please download it! It will help you understand the following.

Here is what we will be making..nice, simple pagers! (Dont worry about the Image #x text, thats really not part of the tutorial)
PHP Automatic Pagination/Simple PHP Paging Tutorial

Paging in php and automatic pagination is something every coder has to deal with when coding in php. I mean, you COULD show all results on 1 page and skip the php paging, but paging is necessary to reduce bandwidth and organize content. Paging is very easy to do and I will walk you through it step by step.

PHP automatic paging comes with a few questions:
Paging 1 : Page Size - How many results would you like to display per page?
Paging 2 : How can we bring back proper results in mysql?
Paging 3 : How can we print a pager that will help show the next items.

Decide on your page size - 10, 15, 25, 50, 100. It really depends on what you would like to do. For this tutorial I will use 15.

//we want 15 results per page

$pgsize=15;

//if there is a p variable in the query string e.g: page.php?p=5 we will get this value, else we will use 1 (page 1)

$pg=(is_numeric($_GET["p"]) ? $_GET["p"] : 1);

//lets determine where we would like to get results from
//if $pg is 1, this calculation results in 0 (we want to start from the first record in the database)
//if $pg is 2, this calculation will result in 1*15..which means we will start at the 15th index of the database (row 16)

$start=($pg-1)*$pgsize;

//let us query the database for our results
//you will notice LIMIT and $start and $pgsize.
//On page 1, this query will be SELECT * FROM image_table LIMIT 0,15 - this means return 15 rows starting at row-index 0 (row 1)
//On page 2, this query will be SELECT * FROM image_table LIMIT 15, 15 - this means we will return 15 rows starting at row-index 15 (row 16)
//On page 3, this query will be SELECT * FROM image_table LIMIT 30,15 - this means we will return 15 rows starting at row-index 30 (row 31)
GET IT?!?!?!

$imgs=mysql_query("SELECT * FROM image_table LIMIT $start, $pgsize");

//we will also need the total number of records in our table
//notice there is no limit? we want to know how many records are in the entire table!
//we can use COUNT(*), COUNT(1), or COUNT(fieldname), they will all return the same result

$img_total=mysql_query("SELECT COUNT(1) FROM image_table");

//mysql_query returns a resource id, we can use this to get the row it has returned

$img_total=mysql_fetch_row($img_total);

//the count will be the first field in this row

$img_total=$img_total[0];

//lets determine how many pages we will need
//WRONG!, this will cut off results..why?
//say we have 31 images, and our page size is 15. 31/15= ~2.x...We need to round this result up!

$max_pages=$img_total / $pgsize;

//use this line instead

$max_pages=ceil($img_total/$pgsize);

Once we have all this information, we can use a handy little function I have written named printPager. This function will print out a neat little pager. It uses a helper function named add_querystring_var which was from Added Bytes here:
http://www.addedbytes.com/code/querystring-functions/

Copy/paste this function into your page or into one of your includes:
This will print out your awesome little pager! :)

PHP Automatic Pagination Function

function printPager($max_pages,$pg){
print '<div class="clear"></div>';
print '<ul class="pager">';
$i=1;
if($pg!=1){
$url=$_SERVER["SCRIPT_NAME"];
$url.=add_querystring_var("?".$_SERVER["QUERY_STRING"], "p", $pg-1);
print '<li class="prev"><a href="'.$url.'"><<</a></li>';
}

while($i<=$max_pages){
$url=$_SERVER["SCRIPT_NAME"];
$url.=add_querystring_var("?".$_SERVER["QUERY_STRING"], "p", $i);

if($pg==$i){
print '<li class="current">';
print '<span>'.$i.'</span>';
print "</li>";
}else{
print "<li>";
print '<a href="'.$url.'">'.$i.'</a>';
print "</li>";
}

$i++;
}

if($pg!=$max_pages){
$url=$_SERVER["SCRIPT_NAME"];
$url.=add_querystring_var("?".$_SERVER["QUERY_STRING"], "p", $pg+1);
print '<li class="next"><a href="'.$url.'">>></a>';
}
print '</ul>';
print '<div class="clear"></div>';
}

function add_querystring_var($url, $key, $value) { $url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&'); $url = substr($url, 0, -1); if (strpos($url, '?') === false) { return ($url . '?' . $key . '=' . $value); } else { return ($url . '&' . $key . '=' . $value); } }

Print Pager is called like so:

PHP Pager Styles

We can style this pager using the following:
/*pagers*/

div.clear{clear:both;}
/spacing between numbers and sizes
ul.pager li {
float:left;
margin-right:5px;
font-size:8pt;
padding: 2px 5px 2px 5px;
}

//link color
ul.pager li a{
color:red;
}

//link hover style
ul.pager li a:hover{
text-decoration:underline;
color:red;
}

//current page styling
ul.pager li.current span{
color:red;
}

//previous and next stylings
ul.pager li.prev, ul.pager li.next{

}

Download this tutorials script! It will help you understand. Right click: php-automatic-pagination-tutorial.php and click Save as. Then get rid of the .txt extension and name it php if you would like to run it. You will need to setup a database table to use for the tutorial. It can have an id field and another field.

If you enjoyed this post please leave a comment! I like reading and responding to all my readers!
Thanks


Use HostGator 2010 Coupon Code: 994offhgpackage for $9.94 off your first month!
(First month will cost $0.01)

9Mar/101

Google SEO Flash & Flash Tips/Techniques

Google SEO Flash

Google currently DOES index flash, however, I believe it is extremely unreliable. Clients have asked me to do some SEO work on their sites, little did I know, these sites were flash!

Most crawlers seem to have a hard time crawling flash and the #1 tip I can give for Flash SEO is: don't show search engine crawlers flash, show them alternate content!

The reasoning behind this technique:
1) Underlying HTML Content
2) Use javascript to load Flash
3) GoogleBot = No Javascript = Doesn't see flash, sees alternate content

For two of the sites I have worked on, I have used JQuery, JQuery SWFObject Plugin, and a base HTML site to get these sites indexed. Search engine crawlers do not have javascript,  so we will use it to load our flash. If our client has flash and javascript, our client will see Flash. If they dont (Googlebot doesn't have Javascript) they will see our underlying HTML content. Let's take a look at this code:

<div id="flash"></div>
<div id="altContent">
<h1>Google SEO Flash Tips and Techniques</h1>
<h2>How To SEO Flash for Google</h2>
</div>
On your main page, write <div id="flash"></div>, then wrap your Search Engine Optimized code in <div id="altContent"></div>.

As you can see, the content in the "altContent" div, is pure html which we can apply the following Basic SEO Techniques to. We have an empty div above with the id "flash". We will use JQuery & the SWFObject to load our flash file into our "flash" div. Since the flash loading is done using javascript, Search Engine Crawlers will not see the flash, but will see our optimized HTML content.

Download a copy of JQuery here: http://docs.jquery.com/Downloading_jQuery
and SWFObject plugin here:  http://jquery.thewikies.com/swfobject/downloads
We will put all our files in the same directory for simplicity, you can put them in a seperate 'scripts' directory if you want to keep organized.

On our main page, we will add the script references (order is important! first load jquery, then the swfobject plugin):<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.swfobject.js"></script>

Now, underneath this, we will add the function to load our flash file:

  1. <script>
  2. $("document").ready(function(){
  3. if($.flash.available){
  4. $("#flash").flash({
  5. swf: 'main_flash8.swf',
  6. width:766,
  7. height:750
  8. });
  9. $("#altContent").css("display", "none");
  10. }
  11. });
  12. </script>

This code should be pretty self explanatory, but, let me explain:
Line 2: We are setting up a function to run when our document has been loaded.
Line 3:Check that the user has the flash plugin and it is enabled
Line 4: We are using the .flash() method of SWFObject to load content into the #flash div. (# stands for id  . stands for class)
Line 5: We set the swf: parameter to our swf file
Line 6/7: We set the width/height
Line 9: Now that our flash has loaded, we set the display of the altContent div to none, which will hide it.

Since GoogleBot does not have javascript, the code to load the flash and hide the altContent will never run.
If a user has flash, the flash site will load. If not, they will see the html content.

Searching for my clients business name, they could not be found anywhere. Once I applied the technique above, they were #1 within a week (Search engines do take some time :) )

This technique is widely accepted. For some more reading, check out: Google Does Index Flash

Hope this article helps.
Comment if it did!

19Sep/091

Professional Table Styling using CSS

On this blog, I have a post about using jquery to apply alternating table row coloring. Someone commented that they couldnt quite get it working and needed an example. So, while making the example for him, I figure it would be a good post to show how to style a table professionally with CSS.

So, were going to start with this markup:
Note: You only need to load jquery and jquery.scripts if you want to do the last part of this example
.

<html>
<head>
<title>Table Row Coloring Example</title>
<script type="text/javascript" src="jquery.js"></script> <!--load jquery-->
<script type="text/javascript" src="jquery.scripts.js"></script> <!--load our custom jquery file-->
<link rel="stylesheet" type="text/css" href="style.css"/><!--load our css styles-->
</head>
<body>
<table>
<th>id</th>
<th>First name</th>
<th>Last name</th>
<tr><td>1</td><td>Scott</td><td>Moniz</td></tr>
<tr class="row2"><td>2</td><td>Bob</td><td>Barker</td></tr>
</table>
</body>
</html>

Alright, now that we have that done. We area going to create style.css and add a few rules.

Here is the table selector:
table{

border: 1px solid #ccc;
}

well....that doesnt look very good..YET.
Lets add a rule to the header. We'll add a background color.

table th{
background-color: #ccc;
}

Lets add a rule to the table data tags.
table tr{
border: 1px solid #ccc;
}

Now, lets see what we got so far.
tabletut1Not too bad. You'll notice the headers are a little to close, and the borders dont look too great. Don't worry well fix that. Lets add another couple rules to table th and td.
table th{
border: 1px solid #000;
padding: 5px;
}
table td{
padding: 2px;
}

Alright..lookin good so far. Here's what you should have:
tabletut2Lets take care of these ugly borders.

On our table selector we will add this rule:

table{
border-collapse: collapse;
}

If you look at the table, you'll notice that on the 2nd row there is a class="row2". We will now style that class.
table tr.row2{background-color: #EBEBEB;}

DONE. The final result looks like this.

tabletut3

You can always modify the styles as you wish.

Tip: Every 2nd row, add the class="row2" to the row to get the alternating row colors. Optionally, add text-align: center; to the table selector.
tabletut4Here's the full CSS:
table{border: 1px solid #ccc;border-collapse:collapse; text-align: center;}
table th{background-color: #ccc; padding: 5px; border: 1px solid #000;}
table td{border: 1px solid #ccc; padding: 2px;}
table tr.row2{background-color: #EBEBEB;}

Keep reading for an easy way to alternate row colors when you have a lot of rows.

Alright, now, if your table has 20 rows, maybe even 50, or 100, adding row2 manually is really a pain...and I personally wouldn't do that. We will use jquery to color the alternate rows.

Find the <tr class="row2"> and change it to <tr>. If you load the table you'll notice the alternate rows aren't colored anymore. We will now add a class to the table. So <table> should look like this <table class="altcolor">.

Now that our table is setup, we will use a jquery selector to color rows in any table that has the class altcolor.
You should have jquery.js and you should create a file named jquery.scripts.js.
Open jquery.scripts.js and add the following:

$("document").ready(function(){
$("table.altcolor tr:even").addClass("row2");
});

This loads when the webpage is ready
//Notice the selector ?
table.altcolor tr:even means any even row, in a table, that has the class "altcolor"
Now we just call addClass, which will add the class row2.
now, the class row2 is added to every even row in a table with the class altcolor.

Done. :)
If you don't get the same result, you might want to download the example source and check it out.

Download Table Styling Example

Tip: When using jquery to style alternate rows, check your table with javascript disabled.
For example, if you style your tables to have white text, and your row2 is supposed to apply a dark background to make the white text show up, if they have javascript disabled, they won't see the white text. Be careful and make sure your table looks good with and without javascript.

15Sep/094

Easy, Simple Paging Using PHP

Easy & Simple Paging using PHP. Here is the result: (DB has 8records, Rows per page is set to 5, and we're on page 2)
advertisers

Paging usually takes a while but here we will do it quickly and cleanly.

Your page will be named page.php. And when we want to switch pages we will make it page.php?pg=2.
Im sure you've seen this before. Anyways lets dive in.

I use shorthand to clean stuff up, but basically shorthand is

$returnvalue=(condition ? "true" : "false");
Example:

$is_loggedin=(isset($_SESSION["loggedin"]) ? 1 : 0);
After this statement, if the session variable is set, $is_loggedin will equal 1, else it will equal 0.

At the top of your PHP page type the following:

<?php
/*paging*/
Line 1: $pg=(isset($_GET["pg"]) && is_numeric($_GET["pg"]) && $_GET["pg"]>0 ? $_GET["pg"] : 1);
Line 2: $rowsperpage=10;
Line 3: $offset=($pg>1 ? ($pg-1)*$rowsperpage : 0 );
Line 4: $limitstr=" LIMIT $offset, $rowsperpage";
?>

Explanation:
First of all Limit is : LIMIT $startrowid, $number of entries to return
So LIMIT 55, 5 means start at row 55 and return 5 rows (55, 56, 57, 58, 59)

Line 1: If in the query string the pg is set e.g page.php?pg=4, and it is numeric, and greater than 0 we will assign the value of $_GET["pg"] to our $pg variable. If it is not set, or it is not numeric, or zero or less, we set the $pg variable to 1.
Line 2: We set our rows per page
Line 3: If the page is greater than 1, we set the offset to ($pg-1)*rowsperpage. If the page is 1 or less, we set offset to 0.
Line 4: We create the limit string for the sql statement. This will output something like LIMIT x, y.
(rowsperpage set to 10)

In this case page.php?pg=1
$pg = 1;
$offset = 0;
$rowsperpage=10;
$limitstr="LIMIT 0, 10"; //this string will pull 10 rows starting from row 0 (the first row) (rows 0-9)

In this case page.php?pg=3
$pg=3;
$offset= (3-1) * 10; //offset calculates to 20
$limitstr="LIMIT 20, 10"; //this string will pull 10 rows starting from and including row 20 (rows 20-29)

Ok. Now that we got that out of the way.

We will use a simple query, then we will attach our new limit string (looking at case 2 above)
$sql="SELECT * FROM MEMBERS $limitstr"; //sql = "SELECT * FROM MEMBERS LIMIT 20,10";
$res=mysql_query($sql);
while($row=mysql_fetch_array($res)){

//processing if you need to
}

We also need to know the total count for this table
$sql="SELECT COUNT(memberid) FROM MEMBERS";
$res=mysql_query($sql);
$row=mysql_fetch_array($res);
$total = $row[0];

Now we know the total count.

So we need to calculate the number of pages. That is done by this formula:
($total/$rowsperpage);
Now in the case of 26 members and 5 rows per page. Using this formula 26/5 = 5.2pages, so we need to round up!

$maxpage=ceil($total/$rowsperpage); //max page is now 6.

Ok, we got everything set up :) Just need to print out our paging!
Wherever you want your paging setup add this:

<?php
print '<div class="paging"><ul>';
for($i=1; $i<=$maxpage; $i++){
  if($pg==$i)
     print '<li><span>'.$i.'</span></li>';
  else
     print '<li><a href="?pg='.$i.'">'.$i.'</a></li>';
}
print "</ul></div>";
?>

Then we can do some nice styling (Mess around with margins to setup spacing)
CSS
div.paging {text-align: center; margin-top: 5px;}
div.paging span{font-weight: bold;}
div.paging ul{overflow: hidden;}
div.paging ul li{width: 10px; float: left; margin: 0px 10px 5px 0px;}

This will page across until it hits the edge of the div, then it will move to the next line.

ENJOY and comment ! :)

12Sep/092

Easy Javascript Validation using JQuery

Now, there might be other tools out there, but this is how I do mine. I like to write stuff from scratch but I actually feel like this little script would make life easier for a lot of people. You're free to use this as long as you leave the copyright in there.

First download jQuery and this script: jquery.validator.js (Right click>Save As)
Next, add these lines.

<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.validator.js" type="text/javascript"></script>

When you create your forms create them like this.
The form must have an id, and it must have the class "validate".
Add the class 'req' for any fields that are required.
Coming soon: email, int verification, age, etc.

<form id="contactform" action="whatever_action_you_want.php" class="validate">
<input type="text" name="firstname" class="req"/><span class="val">*</span>
<input type="text" name="lastname" class="req"/><span class="val">*<span>
<select name="country req">
<option value="">Please select</option>
<option value="CA">Canada</option>
</select>
</form>

In your css add these
span.val{visibility: hidden; color: red; font-weight:bold;}

Thats it.

If you guys post comments and subscribe, I can let you know when i further develop this. It will include number verification, email verification, postal code verification. It's very simple and lightweight and will shave time off any project. File (Right click>Save As): jquery.validator

8Sep/090

Embedding flash using SWFObject

Just to save some of you the headache :) . I spent a few hours on this today, and I couldn't figure it out, I've embedded flash many times before and I just couldn't figure out why this time it wasn't working.

Anyways

Using jquery found here: http://docs.jquery.com/Downloading_jQuery
and
jquery swfobject plugin found here: http://jquery.thewikies.com/swfobject/downloads

we can semantically embed flash.

Now a few things:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.swfobject.js"></script>
<script type="text/javascript" src="jquery.myscript.js"></script>

Make SURE these are in this EXACT order.
Load Jquery>Load its plugins>Load your javascript file.

Now on your page somewhere you will have the div you want to load flash into like so:
<div id="myflashdiv"></div>

Open up jquery.myscript.js and type:

$("document").ready(function(){
       $("#myflashdiv").flash({
               swf: 'flash/myflash.swf'
        });
});

Directory Structure:

flash
  -myflash.swf
script
  -jquery.myscript.js
index.html

This assumes you have a flash folder, and the file myflash.swf in that folder.
The path in this case is NOT relative to the script your working in. Think about it this way:
the flash method probably uses document.write to output the correct object tag for your flash.
If your page is on the root of your site and the script is in scripts/jquery.myscripts.js you would think the source for the swf would be "../flash/myflash.swf". But think about that..in index.html if you look at the output it would say: src="../flash/myflash.swf", you should be able to see why thats wrong if you look at the above directory structure.

Anyways, if you didn't know swfobject behaves this way, this could take you quite some time to figure out.
Hope I saved you that time :)

Troubleshooting
Tip 1: Make sure the load order is : jquery, jquery.swfobject.js, then your script.
Tip 2: Make sure the src you're passing in is relative to the page you're embedding on, NOT relative to the script file you're working in.

2Sep/090

Recursing through a directory/filesystem using C#

This will teach you how to recurse through a directory/filesystem using C#..
The problem comes from not knowing how many folders/files exist.
One folder can have many folders inside it, those folders can each have many folders inside it.

I will show you how to recurse through the filesystem and explain it so that you UNDERSTAND it. This isnt for copy-paste.

We will start with a C# console application and pick a path, we'll use C: for this.
First of all, we're going to need the IO namespace. The IO namespace has access to File and Directory methods.

At the top add these lines:

using System; //Just so we can use the shortcut Console instead of System.Console
using System.IO; //Gives us access to file, directory objects

Now, in our "main" method, we are going to write the following:

string path="C:/"; //set the root path we want to recurse through.

//check if the directory exists
if(Directory.Exists(path)){
        DirectoryInfo di=new DirectoryInfo(path);
        //based on a path, this object will give you directory information about that directory
        printDirectories(di);
        //this method will actually go through our directories and print out information
}else{
        Console.WriteLine("Directory does not exist. Press Enter to exit");
        Console.ReadLine(); //when you hit return the program will terminate.
}


Now we will write the print directories method. It takes a DirectoryInfo object as a parameter and will use that to recurse through the file system.

//declared as static because were a console app, this can be private in your application if it a utility method.
2 Important methods we're going to be looking at are in the DirectoryInfo object. They are

public FileInfo[] directoryInfoObject.GetFiles() //returns an array of FileInfo objects
public DirectoryInfo[] directoryInfoObject.GetDirectories() //returns an array of DirectoryInfo objects

static void printDirectories(DirectoryInfo di){
       foreach(FileInfo fi in di.GetFiles()){
              //we are going to run code for each file
              Console.WriteLine(fi.FullName); //this prints out the full file name including the path
       }

      //now that we process this directory for files, we do the same for every subdirectory in this directory
      foreach(DirectoryInfo subDir in di.GetDirectories()){
             //we are going to call the printDirectories method, with the subdirectory as the root.
            //its files will be processed, then its subdirectories will be checked
            //this happens foreach Directory in the current directory
            printDirectories(subDir); //recurse
      }
}

Thats simple recursion. The most common use of this is for populating a treeview and another use that comes to mind is file searching. Keep an eye out for the next tutorial: Populating a Treeview from a file system!

14Aug/090

Creating/Retrieving a GUID object from a string C#

GUIDS are great to use if you ever may need to merge data.
The chances of collision (duplicates) are extremely low.

To generate a new guid, use this code:
Guid g=Guid.NewGuid(); //this generates a GUID object
Guid g2=Guid.NewGuid().ToString(); //this generates a GUID string





There may be a time where in a stored procedure, you have a GUID as a parameter.

In C# you may have to pass this paramater to the procedure.
This is actually very simple.

Given a string that you know is a GUID, you can retrieve a guid object like so:
Guid g=new Guid(myStringGUID);

And thats all folks :)

Filed under: C#, Programming, SQL No Comments
21Jul/093

Custom Javascript Alert and Confirm Dialog boxes

This article will teach you how to make Custom Javascript Alert and Confirm Dialog boxes, and change the button text on dialog boxes.

For the most part, custom alert and confirm dialogs are not possible because alert and confirm dialog boxes are handled by the browser, however, there is a great JQuery plugin that will let you customize your alert boxes. If you don't know JQuery, do not worry, because i'll take you through it step by step. This little customization can make your web application that much more professional.

This will show you a little tutorial on how to make the custom alert and confirm dialogs AND How to return values from a custom confirm dialog box. This is EXTREMELY important. I have seen a lot of tutorials on how to do this, but none of them talk about actually retrieving the value of the response in a custom confirm dialog box..

Custom Javascript Alert Dialog Boxes

Step 1 : Download JQuery

Click on Current Release, you can click Uncompressed if you want to inspect the code, but you should use minified version for production.

In our site, we will make a folder called scripts, and we will put the jquery.js file into this folder.
We will also make a new file in the same folder named jquery.scripts.js.

Step 2: Download JQuery Alerts Plugin

We will put the jquery.alerts.js into the scripts folder, and the jquery.alerts.css into a styles folder.

Step 3: The Setup
In our webpage we will add the references to these file.

<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/jquery.scripts.js"></script>
<script type="text/javascript" src="scripts/jquery.alerts.js"></script>
<link href="styles/jquery.alerts.css" rel="stylesheet"/>

Once we have all these references in, we're ready to write some jquery.

Step 4: Open jquery.scripts.js
Type

$("document").ready(function(){

});

This sets up a function to be run when our document is ready.

In this document.ready function, type
alert('jquery loaded');

Refreshing your webpage, you should see an alert saying "jquery loaded", if you see this, you have setup jquery correctly. If you do not, check the steps above, or hit CTRL+F5, this does a cache refresh and requests a new copy of all the javascript and css files.

We will add a button to our site.
<input type="button" value="Custom Alert" id="customAlert"/>

In our document ready function, we will hook up a handler to handle the "click" event of this button.

$("document").ready(function(){
$("#customAlert").click(function(){
alert('this is an alert');
});
});

If you refresh your webpage (CTRL+F5) and click the button, you should see a normal javascript popup.
Now, change the alert to jAlert.
jAlert('this is a custom alert', 'this is a custom title');

Upon refreshing the page, and clicking the button, you should see a custom grey alert box. The styles can be modified by editing jquery.alerts.css.

If you'd like to read on Custom confirm dialog boxes, please continue reading.
By this point, jquery and the jquery alerts plugin and css should be setup.
Follow the above tutorial until you get to the actual jAlert method.

Comment if this helped! :)

Custom Javascript Confirm Dialog Boxes

Now, we will do a Custom Javascript Confirm Dialog.
The confirm function looks like this
jConfirm('msg', '[title]', [callback function]);

$("document").ready(function(){
$("#btnID").click(function(){
jConfirm('Would you like Ice Cream', 'msgBox Title', function(r){
if(r){
alert('you replied yes!');
}else{
alert('you replied no!');
}
}
});
});
This is the basic implementation of custom confirm boxes, however you can still customize these a little further.

Changing Javascript Alert Button Text

Before calling jAlert or jConfirm, you can set the button text.

$.alerts.okButton="OKAYYYYYYYYYY";
$.alerts.cancelButton="CANCELLLLLLLLLL";

This is also useful for localization.
For example in an english jquery.scripts.js you can have.

$.alerts.okButton = "yes";
$.alerts.cancelButton = "no";

And in a french jquery.scripts.js you can have

$.alerts.okButton="oui";
$.alerts.okButton="non";

Hopefully this helped you add that little extra touch.
For reference, here are the 2 methods, only the msg parameter is required.

jAlert('msg', '[title]', [callback function]);
jConfirm('msg', '[title]', [callback functoin]);

There you have it!
Please comment if this was helpful :)
Goodluck with your custom javascript!

17Jun/090

Using javascript to opening a new window W3C Validation target="_blank" alternative

<a href="http://www.google.com" target="_blank">Google!</a>
Perfect way to open a new window right? WRANG! (End of the world flash reference ...look it up)

Your webpages may not pass W3C validation because your still using target="_blank".
This article will show you how to use javascript or jquery to open a new window, and have your webpages pass W3C Strict Validation.

Anyyyyyyyyyyyways, using the target attribute of the a tag was a perfectly valid way of opening a link in a new window. However, this currently does not pass certain XHTML Validations. I assume you found this blog post because you need to validate and target="_blank" isn't passing.

This solution will open your link in a new window.
<a href="http://www.google.com" onclick="window.open(this.href);return false;">Google New Window!</a>

What this does is use window.open, and passes the links href attribute as the url.
The reason for "return false", is so that the base web page does not open the link as well.

Another cool alternative is to use JQuery...ya I know this is javascript but if you have jquery already loaded you can add this to your document.ready function.

$(document).ready(function(){
$("a.newWin").click(function(){
window.open($(this).attr("href"));
return false;
});
});

<a href="http://www.google.com" class="newWin">Google</a>

Any link with the class newWin will now open in a new window.

Both these methods validate to XHTML Strict and are easy to implement.

Enjoy.