Sell PHP, JavaScript, C++, C# and Other Scripts and Tools on Jafty.com

Yes, we have started a store on Jafty.com which can be found at Jafty.com/shop. Currently shoppers can find a limited collection of my own scripts and tools for sale. I would like to give my readers a chance to sell their own script and tools here as well, so I am opening it to the public upon approval by me of course. As long as I can see that your scripts are useful and have a potential that someone visiting my site will purchase them, I will publish them. To submit your script for review, simply send me an email at linian11@yahoo.com with a link to your script or attach it to the email and include the amount you expect to receive for each sale made and I will promptly give you a decision on whether or not we will sell your items on Jafty.com.

Email Ian at linian11@yahoo.com to sell your scripts today! Visit our script and tool shop at Jafty.com/shop

Creating a Web Development Environment

This week, I decided it was time to upgrade my web development tools so I contacted the professionals at SEO Root and got right into business. When you reach my age and have been coding for over 20 years, you have to upgrade every once in a while. I am doing this because I know there are faster and better ways to do what I do everyday. I also wanted to document the new system I create for myself as a seasoned web developer so that those of you just starting out can gain some insight.

Defining your Development Needs

First, I had to layout what my needs as a web developer were. I simply made a list of the technologies I use every day and some I use regularly but not every day necessarily and ordered the list in order of priority. The first items on my list are technologies I use the most:

  1. PHP
  2. HTML
  3. CSS
  4. JavaScript
  5. MySQL
  6. WordPress
  7. Woocommerce
  8.  jQuery
  9. Photoshop
  10. SEO
  11. Three.js 3D programming
  12. FTP
  13. Perl
  14. C++
  15. C#
  16. Ajax
  17. Blender
  18. Gimp
  19. Unity 3D Development
  20. XHTML
  21. XML

As you can see, I use over 20 web technologies in my day to day work and I didn’t even list them all, but those are the most significant ones off the top of my head that I use. My goal is to put together a work environment with the most important of those technologies in mind, and so have hired SEO consulting services to aid me with this. Ultimately I wish to create an environment that focuses on speed and the ability to make the top technologies I use to work together in a more organized fashion. For example an app that allows me to code in many languages and preview server-side code live in a local server would be one of the primary objectives of my new routine.

With that in mind, I am going to narrow down my above list to what I use in my day to day work from which I actually make money from and do the most. Those would be mostly the ones at the top of my list, but this gives me the opportunity to rethink what I need the most and come up with a work environment that best facilitates my needs as a web developer. Here’s what I came up with in the end:

  • PHP
  • HTML
  • CSS
  • JavaScript
  • MySQL
  • WordPress
  • Woocommerce
  • Graphic Design
  • SEO
  • FTP
  • Perl

Several of the items in my first list were related to JavaScript such as jQuery, Three.js and Ajax, so really, my main objective is to just have JavaScript available in my work environment and it will basically cover all the related technologies as well for the most part. There is no way we are going to make an efficient work environment with over 20 technologies, so it is important to narrow your list down as much as is practical. There were also a few different methods of creating graphics on my first list and instead of naming Photoshop, Gimp, Blender, etc, I just put “Graphic Design” on my short-list because that enables me to think in more broad terms about what applications I can use that might be able to accomplish the same tasks as those tools all rolled up in a more advanced tool(if that is possible). I will need to consult the specialists from superior web design in Ottawa to make sure I am doing it the right way.  If you  look to design and build your new website, or redesign and upgrade your existing site, visit https://www.akeaweb.com/accessibility-consulting/ .

Searching for Applications

My next task was to find programs and applications that will help speed up the web development process. First, I will list the programs and applications I use currently and from there figure out where I can make improvements. So I copy and paste my short-list from above and add after each technology what tool or program I use to accomplish tasks related to each technology:

  • PHP ——————- Notepad++, Filezilla, Firefox, IE, Safari, Chrome
  • HTML —————– Notepad++, Filezilla, Firefox, IE, Safari, Chrome
  • CSS ——————– Notepad++, Filezilla, Firefox, IE, Safari, Chrome
  • JavaScript ———– Notepad++ , Filezilla, Firefox, IE, Safari, Chrome
  • MySQL —————- Notepad++, PHPMyAdmin, Firefox, Putty
  • WordPress ———– Notepad++, wp-admin, Filezilla, PHPMyAdmin, Firefox, IE, Safari, Chrome, Putty,
  • Woocommerce —– Notepad++, wp-admin, Filezilla, PHPMyAdmin, Firefox, IE, Safari, Chrome
  • Graphic Design – Photoshop, Gimp, Blender, Unity, MakeHuman, FileZilla, Firefox, Notepad++
  • SEO ——————– Notepad++, Firefox, Various Service Providers
  • FTP ——————– Filezilla, Notepad++
  • Perl ——————– Notepad++, Putty, Filezilla

So from the above exercise, I was able to make a comprehensive list of the programs and applications I use when doing my web development work:

  1. Notepad++
  2. wp-admin
  3. Filezilla
  4. PHPMyAdmin
  5. Firefox
  6. Internet Explorer(IE)
  7. Safari
  8. Chrome
  9. Putty
  10. Photoshop
  11. Gimp
  12. Blender
  13. Unity
  14. MakeHuman

So out of those 14 programs, I don’t actually use them all everyday and I use some more than others. For example, I am more of a programmer than a graphic designer. That’s why I call myself a “Web Developer” and not a “Web Designer”. So numbers 10 – 14 on the list can go into my “Nice to Have” category and do not require crucial changes since I only use them every once in a while and it’s not a huge deal to keep using what I use now for those. If you are primarily a web designer however, these applications would be higher up on your list of tools you use and you WOULD want to give more thought to whether you can find better tools and tools that can combine the abilities of several of those. For example, Photoshop can do everything Gimp can do for the most part, so you might want to drop Gimp as a regular tool and use Photoshop more often. Then Unity, Blender and MakeHuman are all 3D modeling tools used more for video game development than web development, but if you use these regularly, you can probably search and find a tool that does most of what you need to do using those tools all rolled up in one good tool. Actually Unity is close. I try to learn to do what models and textures I can right in Unity instead of going to Blender to create them and then import them into Unity which takes more time, but sometimes it is still necessary to do.

Anyway, being first and foremost a web developer and not a designer, the tools most important to me right now are the first ones on my list and can be narrowed down to these:

  1. Notepad++ is what I currently use for most of my coding needs.
  2. PHPMyAdmin is a must have for all of my MySQL database manipulation needs currently.
  3. Filezilla is what I always use to download files from client’s web servers. Then I edit them and upload them back to the server using Filezilla once again.
  4. Firefox is my web browser of choice since it is by far the most standards compliant of all the available popular web browsers. The others listed above are only used at the end of a project to check for cross-browser compatibility and there is no real way to get around having to use them all to properly debug your web applications.
  5. Putty is a great tool I also use often to access client’s web servers for just about anything that I cannot do through the Filezilla FTP program. Tasks I use Putty for include tweaking PHP settings, changing ownership of files and editing server configuration files.

The next thing I have to ask myself is where can I make improvements in my development process and what tools are involved. After that I can search for better tools to accomplish those goals. From what I gather after examining my own habits and tools that I use, I figure the most improvement can be made in the areas of FTP, Code editing and Previewing the results of the code I write.

I came up with the above conclusion by thinking about where it seems like I waste the most time. Also I kept in mind what is possible to change and I figured that recent developments in developer tools probably will allow me to be able to improve the way I edit code, the way I update files and the way I view server-side scripts while in the process of coding them. Here’s my current most common process in my day to day work routine:

  1. I go to Firefox and locate the problem on a client’s website or the area of the website that they may want something added to.
  2. Then, I open Filezilla and locate the files involved that need editing on the server and download them to my desktop for editing.
  3. Next, I will normally open Notepad++ and work on the PHP, HTML, CSS and/or JavaScript code until a portion of the solution is accomplished.
  4.  Then I have to use Filezilla again to upload that file back to the web server for testing.
  5. After that, I open the webpage in Firefox to see if it works and to plan what I have to do next.
  6. I go back to Notepad++ and make more changes.
  7. I upload with Filezilla again and again view the progress in Firefox and keep repeating steps 4,5 and 6 until the changes appear correct.
  8. Then finally, I check the progress in all other popular browsers such as IE, Chrome and Safari to make sure it all works. Again here I have to repeat steps four through six some more until all problems are resolved with cross-browser compatibility.

As you can see, there are some seriously repeated functions that can take up a lot of precious development time in my current process. The best way to speed the process up would be to eliminate the process of having to upload the files to he server every time I make a round of changes and view it in a browser then go back to notepad++. With this acknowledgement in mind, I need to find a tool that allows me to do the following important steps in my web development process:

  1. edit several types of code in one place.
  2. get the code to the server seamlessly for testing.
  3. and view the output in a browser.

So the best place for improvement in my process is within those three steps. If I could find the perfect tool to accomplish all three, that would be perfect.

Finding Tools to Improve your Workflow

So, while looking for tools to accomplish these feats, Here is what I found.

CyberDuck

The first one I tried after reading reviews and program descriptions all across the web, was a not-so-well-known application called CyberDuck. After testing CyberDuck for about a week or so, I found that it met most of these needs, but had it’s pros and cons like any other application. Let’s examine those pros and cons:

CyberDuck Pros:

  • allows for the importing of FTP connection information from Filezille to CyberDuck. This is great because if you have a lot of clients like I do, you have a lot of FTP connections and it would take a lot of time to copy them all manually. In CyberDuck, they call FTP connections “bookmarks” this was strange to me and I didn’t know what they were for the first day or so, but once I figured out what they were, I was able to use the application much more efficiently.
  • CyberDuck has an FTP application built in.
  • It allows you to link your favorite text editor or code editor to the FTP function so all you do is click on a file in the server’s document tree and it opens in an editor on your local machine! So, it downloads a copy of the file and opens it in your editor in other words. So in my case, I click on a file in the document tree and it opens up in Notepad++ for editing.
  • When I save the file after making changes in Notepad++, it automatically uploads the changes to the remote server without me having to do anything but click on “Save” in Notepad++. This saves a lot of time. Even though I am actually using two programs, CyberDuck and Notepad++, it seems like I’m only using one because there is a nice seamless integration of the two performed within CyberDuck.

Cons of Using CyberDuck

There are not a lot of cons, but the ones that bothered me were:

  1. It drops the connection to the server more often than Filezilla did it seems like.
  2. While it combined two of my three main functnionalities I was seeking, it did not allow for viewing of the code changes live on the server. I still would have to go to Firefox to do that.

All in all, CyberDuck is a great tool. It is still new and has some bugs to work out, but I will definitely follow it and use it while looking for a better solution. Perhaps it will evolve into that perfect solution in a future version. Who knows.

CodeLobster PHP Edition

Next I got an email to let me know of a new program called CodeLobster that was supposed to be the perfect PHP code editor and much more. I am giving it a try right now, so I’ll have to come back with most of my review of CodeLobster, but right out of the box I notice that it has a wide range of code editing abilities and features, is expandable and very well made. The only drawbacks I’ve noticed so far are minor such as the word wrap feature breaks up words in bad places and there is no spell check that I can find for editing plain .txt files. It seems great for editing PHP code so far though.

To get expert help regarding SEO and web designing, go to TheDigitalSwarm.com and opt for their services.

Want to learn more about SEO? Check out these relative books from Amazon:

Edit Files Live on the Server

I’ve been a web developer for many  years now and I must say I feel a little foolish for not thinking of this earlier. I’ve been wasting countless amounts of time waiting for files to upload and doing the mundane tasks involved in updating files and uploading them to a server when I didn’t really have to. Here’s why.

Today I got fed up with editing my file in Notepad++, switching to Filezilla,  finding the file in a folder on my desktop, uploading the file by dragging it to Filezilla and finally testing my online website or app. I decided to Google the term “Edit files live on server” and found https://cyberduck.io/ that has an amazing product which allows you to type in your FTP details, just like I used to in Filezilla, and open a connection to my server. Then it gives me a directory tree on my server. CyberDuck allows me to click on any file on my server and open it in Notepad++ on my desktop, edit it and save it right back to the server without having to click and drag it to another program like I used to do for so many years.

This is the best program for a developer I have found in years. Traditionally I do not favor fancy programs to help you write code or frameworks to make things “easier” because I found that they only complicate matters in the long run, CyberDuck is the exception however. It is great so far, but I’ve only been using it for an hour now, so if I find any flaws, I will report them here asap. I just wanted to share this. If you are interested in downloading the CyberDuck app for yourself, simply CLICK HERE or the link above and look for the two download links on the left side of the page. Do not use the first download link you see at the top of the page because it is a sponsored ad and will try to trick you into downloading something else. I hate those types of ads, but none-the-less, I still recommend CyberDuck!

Like I said, it’s great when used with Notepad++, so if you’d like the experience I had, download Notepad++ too. Just google it, it’s easy to find.

The New Ajax

Okay, as a developer, I’ve been using Ajax for years. To be honest, it gives me a new ulcer every time I have to use it. Well, it still does lol, but not quite as bad. Today Ajax technology mixed with jQuery makes it almost tolerable to code with. Also, what’s important, is that it is a very necessary technique if you want to go anywhere at all with your coding skills. Let me demonstrate how to make it easier for everyone. It is not really that hard if you break it down into the simplest form possible and then expand from there. Here is a simple Ajax call to get the results of a PHP script:

Update – I’ve decided to expand this article to include just about every way possible to send data to a PHP script and get a response, so I’ve include the JavaScript/Ajax method, the jQuery/Ajax method and the CURL method of sending data to a PHP script and getting back other data or manipulated data.

Simple JavaScript Ajax call to PHP script:

<!DOCTYPE html>
<html>
<head>
<script>
function get_txt(){
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }else{// code for IE6, IE5
  xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
  }
xmlhttp.onreadystatechange=function(){
  if (xmlhttp.readyState==4 && xmlhttp.status==200){
    var returnval=xmlhttp.responseText;
alert(returnval);
    }
  }
xmlhttp.open(“GET”,”phpscript.php”,true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type=”button” value=”TEST” onclick=”get_txt()” />
</body>
</html>

The above Ajax example will only retrieve data from the declared file. It could be altered to send data to it and receive a response, but I’m saving that gem for my next example using jQuery and Ajax to send a variable to a PHP file and get back a response.

Simple jQuery Ajax call to PHP Script that Returns Data:

The following jQuery and Ajax script will send the “user” variable holding the text “Ian” to the PHP script which will read the “user” variable with $_POST[‘user’] and send the results of the PHP code back to the Ajax script!

<script type=”text/javascript” src=”jquery.js”></script>
<div id=”status”></div><hr>
<div id=”rez”></div>
<script>
//var $j = jQuery.noConflict();//use j. instead of $ if needed

$.ajax({               
    type: “POST”, // the kind of data we are sending
    url: “update_scores.php”, // this is the file that processes the form data
    data: {user:’ian’}, // this is our serialized form-like data to pass to php
    success: function(msg){    // this function runs when the data has been successfully processed
        // this sets up our notification area for error / success messages
        $( document ).ajaxComplete(function( event,request, settings ) {
            $( “#status” ).append( “<p>Request Complete.</p>” );
            preresult = msg;
            $( “#rez” ).append( “<p>”+msg+”</p>” );
        });
            

    }
});
</script>

Sending Data to a PHP script and getting a response using CURL

Note that you could use CURL to do the same thing still using:

        $data = array(‘username’ => ‘ian’);
        $results= curlPost(‘http://www.jafty.com/job.php’, $data);

function curlPost($url, $data){
// check for URL and data:
    if(empty($url)){
        return ‘Error: missing URL’;
    }
    if(empty($data)){
        return ‘Error: missing Data’;
    }
//get the data for the POST and put in URL:
$fields_string = ”;
foreach($data as $key=>$value) { $fields_string .= $key.’=’.$value.’&’; }
$fields_string = rtrim($fields_string,’&’);
//open connection
$ch = curl_init();
//Set the URL, no. of POST vars and POST data:
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($data));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//timeout after 10 secs(change as needed):
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);
//curl_setopt($ch,CURLOPT_HEADER,false);
//Set to return data instead of printing:
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
//pass user agent:
curl_setopt($ch,  CURLOPT_USERAGENT , “Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)”);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//execute post:
$result = curl_exec($ch);
//close connection:
curl_close($ch);
return $result;
}//end curlPost function

…to pass a variable to a PHP script and save the PHP script’s results in $results.

JavaScript Remove Item from Array

Here is my quick and dirty, but good and intuitive, method for deleting an item from an array. The example below is given in a loop and also demonstrates how to build an array and get an array’s length. Three in one, you can’t loose with this demo!

<!DOCTYPE html>
<html>
<body>

<p>Click the button to remove two elements from the array.</p>

<button onclick=”myFunction(‘Banana’)”>-Banana</button>
<button onclick=”myFunction(‘Orange’)”>-Orange</button>
<button onclick=”myFunction(‘Apple’)”>-Apple</button>
<button onclick=”myFunction(‘Mango’)”>-Mango</button>

<p id=”demo”></p>

<script>
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
document.getElementById(“demo”).innerHTML = fruits;

function myFunction(frt) {
//iterate over array:
for(i=0;i<fruits.length;i++){
    if(fruits[i]==frt){
    fruits.splice(i, 1);
    }
}//end foreach
document.getElementById(“demo”).innerHTML = fruits;
}
</script>
</body>
</html>

To make the above work, simply save it in a file and call it anything.html and open it in your favorite, javascript enabled, browser such as Firefox. Then click on “-Apple”(minus Apple) and it will remove the Apple. Click on other buttons it will remove the specified item from the array and print the results to the screen for you to confirm.

Note that this demo show you can remove an item from an array by doing this:

fruits.splice(position, number-to-remove);

…where position is the position of the item you wish to start removing items and number-to-remove is the number of items to remove starting at that position. Simple! Play with it and get used to it and it’ll make more sense.

Also note that we demonstrated how to build an array like:

var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];

…and we all know that JavaScript uses Objects instead of traditional Arrays like PHP and other languages use, but it’s all the same for the purposes of this demo.

One more thing this demo shows people is how to get the number of items of an array or the length of an array in JavaScript. That is accomplished like this:

var arrayLength = fruits.length;

Summary

Ab-a-dee-ab-ah-dee, that’s all folks!

 

JavaScript Get Random Number Between X and Y

This is a short demonstration on how you can get a random number between any two numbers specified using JavaScript. Here is my random number generating function I use often during 3D game development:

function randomNo(x,y){
return Math.floor(Math.random() * ((y-x)+1) + x);
}//end randomNo

A very simple function that gets the job done while saving you some thinking time! You can make pass any number you want, positive or negative, to the randomNo function shown above. For example:

for(i=0;i<100;i++){
var ans = randomNo(-25, 25);
document.write(i+”) “+ans+”<br>”);
}

The above usage case would return something like this:

0) 14
1) -16
2) -13
3) -10
4) 22
5) 17
6) -3
7) 20
8) 22
9) -25
10) 14
11) -16
12) 18
13) 14
14) -7
15) 10
16) -19
17) 11
18) 10
19) -21
20) -20
21) -6
22) -3
23) 12
24) 5
25) 21
26) -23
27) -6
28) 17
29) -9
30) 10
31) -4
32) -14
33) -7
34) -20
35) 8
36) 7
37) 0
38) 21
39) -17
40) 6
41) 4
42) -1
43) 10
44) 12
45) 16
46) 18
47) -12
48) 9
49) 21
50) -6
51) 19
52) -23
53) 9
54) 17
55) -2
56) 9
57) -21
58) -18
59) 19
60) -24
61) -10
62) -20
63) 19
64) 0
65) 0
66) 8
67) -9
68) -15
69) -13
70) 11
71) 22
72) -7
73) 16
74) -16
75) 2
76) 19
77) -25
78) -3
79) -19
80) -23
81) 13
82) 17
83) 8
84) -15
85) -19
86) 22
87) -1
88) 12
89) 14
90) -11
91) 24
92) 12
93) 9
94) 9
95) 18
96) 22
97) -5
98) -25
99) 25

The above results are from an actual deployment of the code shown above.

To understand how my random function works, you should know that the Math.random() function returns a value between 1 and 0. You should also know that the Math.floor(x) function returns the largest integer less than or equal to the number “x”.

JavaScript Play Two Sounds at Once

Anyone following my blog may know I have undertaken 3D web development. This includes games and other 3D content for websites. Sound is particularly important to video game development. When it comes to building games with JavaScript, we have to know how to handle multiple sound files at once.  I actually tried a lot of tricks before I found this simple jQuery solution that works:

<script src=”http://code.jquery.com/jquery-1.8.0.min.js”></script>
<script>
$(document).ready(function() {
console.log( “Ian says the document is ready!” );
var audio = new Audio(‘sounds/beat.mp3’);
audio.play();
var audio2 = new Audio(‘sounds/song.mp3’);
audio2.play();
});//end doc ready fun
</script>

Three.js Rotate 3D Text by its Center Point

It took me a few hours to solve the issue of how to rotate text generated by three.js and the THREE.TextGeometry function. That is why I am posting the final solution here for others to find when they have the same issue. When you simply create a 3D text model with THREE.TextGeometry and add rotation to it it will rotate on it’s default pivot point which will be on the first letter of the text. That means it will not rotate according to a center pivot which is what I needed. I tried several types of three.js functions and mods to get it to work that all failed except one. I eded up creating a new pivot object to contain the text object and rotating that. Here is the complete code followed by an explanation of how it works.

<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Jafty 3D Gallery</title>
<meta charset=”utf-8″>
<meta name=”viewport” content=”width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0″>
<style>
body {
background: transparent;
padding: 0;
margin: 0;
font-family:sans-serif;
}

#canvas {
margin:10px auto;
width:800px;
height:350px;
margin-top:-44px;
}

</style>
</head>
<body>
<div id=”canvas”></div>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/three.js/r69/three.js”></script>
<script src=”js/OrbitControls.js”></script>
<script src=”js/janda_manatee_solid_regular.js”></script>
<script>
// standard global variables
var container, scene, camera, renderer, controls, textMesh2;
//var axis = new THREE.Vector3(0,1,1);

function init() {
// SCENE
scene = new THREE.Scene();

// CAMERA
var SCREEN_WIDTH = 800, SCREEN_HEIGHT = 300;
var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
scene.add(camera);
camera.position.set(0,0,1000);
camera.lookAt(scene.position);
renderer = new THREE.WebGLRenderer({antialias:true, alpha:true});
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
container = document.getElementById( ‘canvas’ );
container.appendChild( renderer.domElement );

// CONTROLS
controls = new THREE.OrbitControls( camera, renderer.domElement );

// LIGHT
var light = new THREE.PointLight(0xffffff);
light.position.set(0,0,1000);
scene.add(light);

// add 3D text beveled and sized
var material2 = new THREE.MeshPhongMaterial({
    color:0xff4444,//default is 0xffffff
    //vertexColors: THREE.FaceColors,//THREE.VertexColors,
    //morphTargets: true,//? doesn’t work here
    shading: THREE.FlatShading,//comment out for other default shading type
    //shading:THREE.NoShading,//uncomment for no shading at all.
    wireframe: false,
    wireframeLinewidth: 1,//windows is always 1, but macs/linux will change line width
    //emissive: 0xFF0300,//color of the material, essentially a solid color unaffected by other lighting. Default is black.
    specular: 0xFF0300,//color of shine
    shininess: 65,//default is 30, higher the shinier
    //reflectivity: 100,//not sure what values are, but didn’t make diff
    //opacity: 0.4,//0.0 – 1.0
    transparent: true,
});

var textGeom2 = new THREE.TextGeometry( ‘Jafty 3D Gallery’, {
    size: 120, //text size
    height: 80, //thicknes of text’s extrude!
    curveSegments: 3,
    font: ‘janda manatee solid’,
    weight: ‘normal’,//normal or bold(both don’t always work with all fonts)
    style: ‘normal’,//normal or italics(both don’t always work with all fonts)
    bevelThickness: 12, //how deep bevel goes into text
    bevelSize: 8, //dist of bevel from text outline
    bevelEnabled: true
});
textMesh2 = new THREE.Mesh( textGeom2, material2 );

textGeom2.computeBoundingBox();
var textWidth2 = textGeom2.boundingBox.max.x – textGeom2.boundingBox.min.x;

textMesh2.position.set( -0.5 * textWidth2, 0, 60 );//left-rt/high/far
scene.add( textMesh2 );

pivot = new THREE.Object3D();
pivot.add( textMesh2 );
scene.add( pivot );
}//end init function

function render() {
renderer.render(scene, camera);
}

function animate() {
window.requestAnimationFrame(animate);
render();
pivot.rotation.y += 0.015;
}

init();
animate();
</script>
</body>
</html>

What part of the above code makes it work?

Good question. All goes according to a normal 3D text reduring until after where I added the textMesh2 object to the scene. Look at the line that starts with the word piviot. Here’s the functional code that allows us to rotate the text by it’s center axis instead of an axis off to the left of center:

Put this in your init function:

pivot = new THREE.Object3D();
pivot.add( textMesh2 );
scene.add( pivot );

Then, place this in your animate or update function:

pivot.rotation.y += 0.015;

What we are doing here is adding a new Object3D to the scene and then adding our textMesh2 object to the pivot object and finally in our update or animate function, we rotate the pivot object containing the text object which rotates on it’s center axis now! You can change the no. in pivot.rotation.y += 0.015; to make it rotate faster or slower. Make it a negative no. to rotate the other direction.

How to Use PHP in an External JavaScript File

This is a simple lesson on making your external JavaScript files more dynamic using PHP. PHP is perfectly capable of generating JavaScript code in-line, but have you thought about using it in an external JavaScript file? Well, you can and here’s how:

1 – Convert your JavaScript file to a PHP file

Let’s say you already have an existing JavaScript file. You’ll have to convert it to a PHP file to be able to enjoy all of the goodness of PHP in your JavaScript. All you have to do is change the .js extension to a .php extension so javascript.js becomes javascript.php.

2 – Edit HTML to Include your External JavaScript/PHP File

The next thing you’ll do is edit the script tag in your HTML that calls your external JavaScript. It will end up looking like:

<script type=”text/javascript” src=”javascript.php?c=<?php echo $config_file; ?>”></script>

Notice that two things are changed from how it would look before converting to PHP. First, we added a variable to the file name and second we added a PHP tag to echo the file name of a third file used to hold PHP variables that need to be available to the JavaScript file since the script tag doesn’t allow for variables in the including script to be passed to the external JavaScript/PHP file automatically as it would if it were included using a PHP include function. NOTE: the passing of the config script is optional, so if you don’t need to pass any PHP variables or functions along in your script tag, all you’d have to do is replace javascript.js with javascript.php and you’d be done. You’ll find the method for passing PHP variables and functions will come in handy for many of you tough.

Back to work. Hope this helps.

How to use Twitter Boostrap without the Overhead

I went over to the Twitter Bootstrap website today to download the latest Bootstrap version for a new project I am starting and was happy to notice that the Bootstrap files are now available as remotely included files! That means you do not have to download the files and put them on your server. They include the two main files, the CSS and the JavaScript files, for Twitter Bootstrap.

How to use remote file includes for Bootstrap

MaxCDN has provide CDN support for Bootstrap’s CSS and JavaScript files. Simply replace old links to CSS and JavaScript files with these Bootstrap CDN links:

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>

 

 

Best Captcha Scripts

Tonight I decided to evaluate a few different captcha options. I did this mainly for the same reason I do most things on this blog, I have a client that needs a captcha. My situation, as usual, is unique because I have to add a captcha to a PHP page, but that PHP page submits a form to a cgi script. As you may have heard, I am mostly a PHP programmer, so I don’t care much for cgi and asp type scripts. I had to find a captcha that would work with both PHP and cgi, which wasn’t easy as it turns out.

Here are some of the captcha solutions I tried. If you want my best reccomendation, skip to the last one, Jafty Captcha. It is a custom simple captcha I made from what I learned examining the others.

BotDetech

Botdetct is a captcha solution that offers solution in PHP, ASP, cakePHP, Ajax and others, so I thought it might work for my unique situation. Turns out it wasn’t the best for my situation, but it would of been great for pure PHP or HTML web pages that need captcha. I did make a working example which you can see at:

http://jafty.com/BotDetect-PHP-CAPTCHA/samples/php_basic_captcha_sample/ian.php

That is a link to the test I ran with it. The only problem with this is that is does the captcha after the form is submitted and I needed a script that can do the captcha check before form is submitted due to the fact that my client’s page submits to a cgi script and I’d rather not mess with the cgi script at all to keep things simple. Back to the drawing board for me, but if you have a PHP only form submission, it would work great for you!

Simple PHP Captcha

Simple PHP Captcha was the next service I evaluated. I like this one better than BotTech for sure, but again, it was a PHP only solution basically offering no JavaScript alternative and the code to check the captcha would have to be on the page you are submitting the form to. This is a good PHP only solution, but if you are not submitting your form to a PHP script, this isn’t ideal, so I kept searching. Here is the example I made for this captcha script though:

http://jafty.com/captcha/test.php

Simple JavaScript Captcha You Can Add to Any Form

I found my next Captcha to test at http://www.tothemoon.com/2013/01/simple-javascript-captcha-you-can-add-to-any-form/ and you can see from the URL, it is supposed to be a very simple JavaScript captcha. So I decided to give it a go. I actually took this script and made some adjustments to it and came out with a decent captcha script which I will post the code for anyone else interested here.

Demo: http://jafty.com/simple-js-captcha/JS-captcha.html

HTML & JavaScript code:

<!DOCTYPE html>
<html>
<head><title>JS Captcha by Ian L. of Jafty.com</title>
<style>
body{
background-color: #430000;
}
</style>
</head>
<body>
<form name=”review” ACTION=”newpg.html” METHOD=”POST” onsubmit=”return checkform(this);”>
<font color=”#DD0000″>Enter Code ></font> <span id=”txtCaptchaDiv” style=”background-color:#A51D22;color:#FFF;padding:5px”></span>
<input type=”hidden” id=”txtCaptcha” />
<input type=”text” name=”txtInput” id=”txtInput” size=”15″ />
<input type=”submit” value=”Submit”/>
</form>

<script type=”text/javascript”>
function checkform(theform){
var why = “”;

if(theform.txtInput.value == “”){
why += “- Security code should not be empty.\n”;
}
if(theform.txtInput.value != “”){
if(ValidCaptcha(theform.txtInput.value) == false){
why += “- Security code did not match.\n”;
}
}
if(why != “”){
alert(why);
return false;
}
}

//Generates the captcha function
var a = Math.ceil(Math.random() * 9)+ ”;
var b = Math.ceil(Math.random() * 9)+ ”;
var c = Math.ceil(Math.random() * 9)+ ”;
var d = Math.ceil(Math.random() * 9)+ ”;
var e = Math.ceil(Math.random() * 9)+ ”;

var code = a + b + c + d + e;
document.getElementById(“txtCaptcha”).value = code;
document.getElementById(“txtCaptchaDiv”).innerHTML = code;

// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById(‘txtCaptcha’).value);
var str2 = removeSpaces(document.getElementById(‘txtInput’).value);
if (str1 == str2){
return true;
}else{
return false;
}
}

// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(‘ ‘).join(”);
}
</script>

</body>
</html>

BotBoot Captcha

A very simple captcha that requires that the use answer a simple math question. It is not quite secure enough to use for the client I have right now, but might be good for sites with less traffic and spam issues. It would be more secure if it would use questions like “six + one = ?” instead of “6 + 1 = ?” so the math could not be calculated by a bot, but it is a start. I might develop this out in the future to include words instead of numbers or a combination of both as I have seen on many sites and works great. Here is the simple version right out of the box I found:

http://jafty.com/botboot-captcha/

 Jafty Simple Captcha

Okay from everything I’ve learned examining the available simple captcha solutions around the web, I decided to make my own since none of the above quite met my client’s specific requirements. I would consider this to be the ultimate simple captcha. It is HTML5 compliant, cross browser capable, Works on both Windows and Mac and is still relatively simple and very easy to install.

DEMO: http://jafty.com/Jafty-Captcha/simple-captcha.html

DOWNLOAD: Click Here to Download

Javascript go back to previous page and refresh

Any half-ass JavaScript guru or newbie knows that you can go back to the previous page with the history.go(-1) statement in JavaScript, but what if you have to do the same thing but with a page refresh? Well one newbie type thought was to use :

<body onload="document.refresh();">

…in the previous page’s body tag, but that’s not cool if you don’t know what the previous page will be or don’t want that page to refresh for people landing on the page another way other than your special link. So, here’s what I ended up using in a link to go back to previous page, no matter what it may be, and refresh it simultaneously:

<a href=’javascript:window.location = document.referrer;’>Click here to refresh and view changes</a>.<br />

Problem solved! Enjoy…

Dynamically Click on a Button with JavaScript

Today I ran into a case where I needed to emulate a button click. How did I imitate a button click? Here is how I did it with a little JavaScript and the click function.

Emulate Button Click with JavaScript

Imagine you have a button with the id of mybutton:

document.getElementById(‘mybutton’).click();

The above JavaScript line will click on that button. What I needed to do is to have a button clicked when someone clicks on a div. Note that it could be any element that is clicked on such as another button or even an image. I did this:

<div style=”width:400px;height:225px;border:1px solid red;” onclick=”document.getElementById(‘buttonb’).click();” />Click on this div to click the submit button…</div>

<input type=”submit” id=”buttonb” name=”buttonb” value=”” />

In the above example, when the user clicks on the div that says “Click on this div to click the submit button…”, the submit button is clicked and whatever form it goes to is submitted. There are various reasons why you might need to use this trick and it is a good one to have in your bag. Notice I added styles to the div to make it visible.

Using JavaScript with WordPress

Tips on Using JavaScript in WordPress

The use of JavaScript in WordPress is a bit of a grey area for some. More advanced users of course know that JavaScript can and is normally used in themes, child themes and template files. We will touch on that in this tutorial and also cover the more uncertain techniques of using JavaScript in posts and pages. Some say it can’t be done. Some people say to use a plug-in and others just don’t know. I will discover a technique that does work for including some JavaScripts in posts and pages. the technique is meant to be used sparingly, but it is a good solution for people who don’t really want to get into making their own templates, themes or child themes just to include some JavaScript in their WordPress blog.

Using a JavaScript Plug-in

HTML JavaScript Adder is one WordPress plugin targeted at people who have a need to include more complex JavaScript’s in their WordPress blog. This plugin is for including HTML, JavaScript, Flash and shortcodes within the sidebar of your blog, so may not be perfect if you need it for the main content area. Some practical uses of the HTML JavaScript Adder plug-in include:

 

  • Advertisements from such companies as Add Bright, Adsense and Buysellads.

  • Embedding flash  – for example: YouTube videos, Video players and games.

  • Installing shortcodes.

  • Share Icons/widgets such as facebook, linkedin, twitter, etc.

 

You can try pretty much any Javascript, Flash or HTML snippet with the plugin and most should work in your sidebar. Of course I haven’t tested it with every type, so feel free to experiment and let us know. you can get the HTML JavaScript Adder plug-in free of charge from http://wordpress.org/extend/plugins/html-javascript-adder/.

 

The Inline JavaScript plugin is the name of another plugin specially developed for using JavaScript in WordPress. The Inline JavaScript plug-in has one major advantage over the HTML JavaScript Adder from above. It allows you to place JavaScript directly in both posts and pages via the WYSIWYG editor. You are not restricted to sidebars as with the previous example. Some of the things the Inline JavaScript plug-in could be used for are:

  • Including almost any dynamic JavaScript code in the midst of a post or page.

  • Making use of built-in JavaScript functions, variables and attributes without hard coding into a template or theme.

  • Printing dynamic content to the screen such as dates, times, user names, etc.

Just about any inline JavaScript code you can come up with is likely to work with this plugin, but it’s not meant for really long scripts and some scripts designed to be in the head section of an HTML page.

 

This is an easy to use plug-in with common install instructions and very easy operating instructions. Basically all you do is install the plug-in and then insert your JavaScript between inline tags as in the following example:

 

[inline]

<script type=”text/javascript”>

document.write(“hello world!”);

</script>

[/inline]

Do you want to try it for yourself? Simply go to http://www.ooso.net/inline-js and download it. It doesn’t get much easier than that and using the tags like above.

Inserting JavaScript Without a Plugin

Now as controversial as including JavaScript in a post or page without using a plug-in is, it actually can be done in many cases. Some code will not work because the WordPress WYSIWYG editor will tear it to shreds, but if it’s done right and within reason, it is very possible. One trick I have learned over the years while working with WordPress is that if you don’t go back and forth from the WYSIWYG view to the HTML view, it often won’t mess up your code, but that is not always practical and it usually means you have to use only the HTML view and if you even switch to the WYSIWYG view, it destroys your JavaScript code. You can also go to your WordPress dashboard and turn off the rich text editor by going to Users then Personal Options. That’s just a tip in case you are desperate enough to try code that really isn’t supposed to work in WordPress.

Back to using JavaScript in posts without a plug-in, it even says in the WordPress Codex that it can be done, so lets discuss how. The codex does caution you to use this method sparingly however, so if you have more than a few lines, it’s not recommended to use this method. If you just have to print a line to the page from a variable or something similarly simple, then this method should work fine in most cases. Here are the steps you want to take to include javascript in a post or page:

First wrap everything in functions. If you have to use more than one or two functions, then you probably want to consider an alternative method for employing the scripts in your posts or pages such as a template file or child theme. More advanced users will more likely chose those alternative methods most of the time anyway.

Second, place your one or two short JavaScript functions into an external JavaScript file.

Upload your script with your functions in it to a scripts directory in your main WordPress directory. That will be the same directory that holds the wp-content and wp-admin folders among other stuff. If you don’t have a scripts directory, create one there.

Insert the code to include the JavaScript file in the spot where you want to call the JavaScript from within your post or page like this:

<script type=”text/javascript” src=”/scripts/updatepage.js”></script>.

Finally insert the function call on the next line in your post or page. It should look something like this:

 

<script type=”text/javascript”>

<!–

yourFunction();

//–></script>

Now that’s pretty simple, but beware, it doesn’t always work. The simpler the code, the better chance you have, but if you want to avoid problems and you are a little more on the advanced side of coding, just use a child theme, thats what I would normally do. It only takes a few minutes to figure out if you have enough knowledge of PHP, JavaScript and HTML to understand the code. In fact, read my other tutorial right here on WPHUB about child themes and it will guide you through the process rather quickly!

Summary

That’s it! I hope this short JavaScript guide for WordPress helps you to understand the ins and outs of using JavaScript. Yes, it’s true that WordPress isn’t very friendly to the non-coder for using JavaScript snippets in posts, you will have to use some workarounds as I have explained above, but for the determined beginner it shouldn’t be impossible and for the advanced user, it should be a breeze. Good luck with your WordPress project and including JavaScript in your next post or page.

Buy Scripts, Applications and Web Tools at Jafty.com/products

Yes, I finally am starting to sell some of my products that I have been developing for over 12 years now. I am only putting together the best tools I have made and remaking certain ones I find the most useful for sale on my website, Jafty.com/products

Types of Products for sale on Jafty.com/products

  • Email Marketing tools
  • Domain name tools
  • DNS tools
  • Server administration tools
  • webmaster tools
  • PHP tools
  • Customized tools for business
  • Have me build one custom for you if you don’t see what you need

CLICK HERE TO VISIT Jafty.com/products/ and see what’s listed for sale now. However, I do not have them all listed yet, so drop me an email or give me a phone call at 330-903-6074 or 330-417-3617 to find out how I can help you.

jafty0

Want to learn more about SEO? Check out these relative books from Amazon:

Simple Ajax Example

Here is a simple Ajax example to grab a value from a PHP file. The same method would be used for a .txt file or a json request value.

JavaScript Code:

function get_txt(){
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }else{// code for IE6, IE5
  xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
  }
xmlhttp.onreadystatechange=function(){
  if (xmlhttp.readyState==4 && xmlhttp.status==200){
    var returnval=xmlhttp.responseText;
alert(returnval);
    }
  }
xmlhttp.open(“GET”,”phpscript.php”,true);
xmlhttp.send();
}

PHP Code:

<?php

echo “This text came from a PHP file!”;

?>

To test, simply save the JavaScript code in an HTML file in the header and save the PHP code in a PHP file named phpscript.php. Then add the following button in the body of the HTML file:

<input type=”button” value=”TEST” onclick=”get_txt()” />

Creating a WordPress Theme From Scratch

There is a lot to learn about WordPress theme development. In this intermediate level tutorial for aspiring WordPress theme developers, I will describe the bare essentials for developing your own responsive WordPress theme from scratch.

 

What is a Responsive WordPress Theme?

When I speak of responsive WordPress themes, I mean a theme that is mobile friendly with elements that change size and sometimes position according to your current screen size. In my opinion a truly responsive web page should look good in any browser window and any elements on the page should self-adjust according to the window size.

 

Dynamic sizing of elements on the webpage is important. This means that elements should change size and sometimes even shift position while you resize the browser window. In other words, you will see the images change size as you resize the window. Other objects can resize as well,but images are often the number one concern. Divs, text and other inline or block objects can also be sized accordingly while the window size is manipulated. Of course this allows for the page to open at any size and size the elements accordingly.

 

File Infrastructure

The first thing you can do to start your theme is create a directory to house your theme in the wp_content/themes directory of your WordPress installation. Name a new directory after the theme you are creating. In this tutorial, we are creating a theme called responsive_jafty so that is what you can call the directory unless you have a more appropriate theme name in mind, in which case you are free to name it as you please of course.

 

The actual files we will be creating will be style.css, index.php, header.php, sidebar.php and footer.php, the bare essentials to get you started in theme development. These files need to be named as stated above or WordPress will not recognize them as it should.

 

Layout

Before you start coding it is crucial to know what you are doing. The very least you should do is draw a basic wireframe with the main areas of your webpage defined as in the following image:

When developing a professional theme, you will want to do a little more than a simple wireframe, but this works for our learning purposes. In real life, if you were developing a professional theme for yourself or a paying client, you would want to develop a detailed Photoshop rendering of the theme you wish to create. You should at least layout the home page or main posts page in Photoshop including all details. The finished Photoshop template should look exactly like the theme you wish to create. However, a wireframe is often a great way to start if you don’t really know what you want or if you are a stronger developer then you are a designer.

 

Creating Your header.php Script

One of the essential files to create a theme is the header.php file. From looking at the above wireframe, I can tell how I will need to code heaer.php. Here is a working example:

 

<!DOCTYPE html>

<html>

<head>

<title>Jafty Responsive WordPress Theme</title>

<link rel=”stylesheet” href=”<?php bloginfo(‘stylesheet_url’); ?>”>

</head>

<body>

<div id=”wrapper”>

   <div id=”header”>

   <h1>Jafty Responsive Theme</h1>

   </div><!–end header–>

 

That’s all there is to a simple header file. It just needs a doctype declaration, opening HTML tags an opening wrapper div and the site’s header div with the contents of the header.

Creating the index.php file

The next essential page for your theme is the index.php file that includes the above header as well as the sidebar and footer files. Here is a working example of a simple index.php page:

 

<?php get_header(); ?>

 

   <div id=”main”>

      <div id=”content”>

      <?php if (have_posts()) : while (have_posts()) :     

 

   the_post(); ?>

      <h1><?php the_title(); ?></h1>

      <h4>Posted on <?php the_time(‘F jS, Y’) ?></h4>

      <p><?php the_content(__(‘(more…)’)); ?></p>

      <hr>

      <?php endwhile; else: ?>

          <p><?php _e(‘Sorry, no posts matched your criteria.’);

 

?></p>

      <?php endif; ?>

      </div><!–end content–>

   </div><!–end main–>

   

 

   <div id=”sidebar”>

   <?php get_sidebar(); ?>

   </div><!–end sidebar–>

 

<div id=”delimiter”></div>    

   

   <div id=”footer”>

   <?php get_footer(); ?>

   </div><!–end footer–>

</div><!–end wrapper div–>

</body>

 

</html>

That’s a very basic working example which you may expand upon as necessary to get the desired results. Now lets move on to the footer and sidbar pages next.

 

Creating Your sidebar.php Script

The sidebar.php script just needs to have a few built in functions from WordPress to get your sidebar objects into your template such as categories and archives as in the following example code for sidebar.php:

 

<h2 class=”sidebartitle”><?php _e(‘Categories’); ?></h2>

<ul class=”catlist”>

<?php wp_list_cats(‘sort_column=name&optioncount=1&hierarchical=0’); ?>

</ul>

<h2 class=”sidebartitle”><?php _e(‘Archives’); ?></h2>

<ul class=”archivelist”>

<?php wp_get_archives(‘type=monthly’); ?>

</ul>

 

That concludes sidebar.php, now move on to footer.php to finish our PHP files.

 

Coding footer.php

The footer.php script just needs to have the content for the footer widget. It is nice to have footer.php file so making changes to one file will change the footer throughout the entire site.

 

<h2>Another WordPress Site created by Jafty Interactive Web

 

Development</h2>

&copy; 2013-2035 Jafty Interactive Web Development.

 

That’s a start, you can add what is appropriate for your own footer.

 

The Magic is in the Style Sheet!

The style sheet is probably the single most important file for a new theme. It is what WordPress uses to recognize the theme and provide information in the WordPress admin area regarding your theme, so be careful to include all the necessary elements indicated in the below example:

/*

Theme Name: Responsive Jafty

Theme URI: http://jafty.com/

Description: A bare-bones responsive WordPress theme example.

Author: Ian L.

Author URI: http://jafty.com/

Version: 1.0

Tags: blue, white, two-columns, flexible-width, flexible-header, http://wordpress.org/extend/themes/tag-filter/

 

License:

License URI:

 

General comments (optional).

*/

body {

text-align:center;

}

 

#wrapper{

display: block;

border: 1px #000 solid;

width:90%;

max-width:1400px;

margin:0px auto;

}

 

#header{

border: 2px #000 solid;

}

 

#sidebar{

width: 35%;

height:500px;

border: 2px #000 solid;

float: left;

}

 

#main{

width: 62%;

border: 2px #000 solid;

float: right;

}

 

#delimiter{

clear:both;

}

 

#footer{

border: 2px #000 solid;

}

There you have it. Notice the tags I used. Those help people searching for themes find what they are looking for, so will help make your theme popular if people are searching for the attributes of your particular theme. There are only certain tags that will work here. For a list of working tags, see: http://wordpress.org/extend/themes/tag-filter/

 

Putting It All Together

Okay, we have laid out all the theme elements above. It is time to put it all together and have a working responsive WordPress theme. It is just a start, but you can build on this. It is fluid and adjustable. When you are done, you will probably want to add a section of JavaScript code or Jquery code to resize images on page resize.

 

Now simply upload all the files to the new theme directory we created at the start of the tutorial, then go to your WordPress installation and activate the theme from the admin console. Simple as that! When you open your site you will see a very basic wireframe responsive theme layout as in the two examples below that demonstrate the way it will look in two vastly different screen sizes:

 

 

Above is a narrow screen size and below is a wider size. Notice the way it behaves:

Using JavaScript in WordPress

Format a Phone Number with JavaScript During Input

How to format a ten digit phone number with JavaScript

Recently I had a project where a client wanted all the phone number fields in their forms to be formatted with only numbers and dashes using a standard ten digit phone number. Here is the solution I found that worked best:

The HTML

Phone Number: <input type=”text” id=”spouseph” name=”spouseph” value=”” onkeyup=”phoneNo(event,this)” />

The JavaScript

//function formats phone numbers like 111-111-1111 during input:
function phoneNo(e,f){
var len = f.value.length;
var key = getKey(e);
if(key>47 && key<58 && len<13)
{
if( len==3 )f.value=f.value+’-‘
else if(len==7 )f.value=f.value+’-‘
else f.value=f.value;
//see if final number is correct:
var rex = /^[d -]+$/
if(f.value.search(rex)==-1){
alert(“Error! Please enter your 10 digit phone number. Dashes will be inserted for you automatically. Only numbers are allowed.”);
f.value=f.value.substring(0,len-1);
}

}
else{
f.value=f.value.substring(0,len-1);
}
}
//getKey function used in above phoneNo function
function getKey(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
return code
//    return String.fromCharCode(code);
}

The getKey function supports the phoneNo function which ensures that users only input numbers and dashes in the proper position. In fact, it inserts the dashes automatically and won’t allow more than ten digits or 12 total characters including dashes. Hopefully some of you will find these simple JavaScript phone number validating functions as handy as I did.

NOTE: I found a but in this function with the shift key, it will allow some other characters, so I will work on a solution…