Category Archives: JavaScript

How to Open and Close Windows with JavaScript from Parent and Child

Today I wasted a couple hours trying to figure out how to close a window that had been opened from a parent page with a button in the child window. I wrote this quick JavaScript tutorial on how to open and close windows from parent and child in hopes that it will help someone else figure it out faster than I did.

To keep it simple, we will use two HTML files in this example and we'll call them open_close_window.html and popup.html where open_close_window.html will be the parent and popup.html will be the child pop up window. open_close_window.html, the parent, will include two JS functions and a button while the child, popup.php will include nothing but a button to close itself. What I found a little odd was that in order to close the child window from within itself, I had to call a function from the parent. Here's how it is done. Below is the full contents of both files:

open_close_window.html content:

<html>
<head>
<script>
var myWin;
function openWin(){
myWin = window.open("popup.html", "myWindow", 'width=600,height=300');
}//end openWin JS function

function closeWin(){
myWin.close();
}//end closeWin JS function
</script>
</head>
<body>
<button type="button" onclick="openWin();">Open Window</button>
</body>
</html>

Notice that I set the var myWin in the first line of the JavaScript code above. It will not work if you do not place the myWin variable in the global scope like this. Also you can not simply name the window in the window.open function call like I thought I could at first, you have to use a variable to reference the window when closing it.

popup.html content:

<html>
<head>
</head>
<body>
<button type="button" onclick="opener.closeWin();">Close Window</button>
</body>
</html>

Summary

I hope you can see how this all works from this simple demonstration. You don't even need to upload the two files to a web server to test them since they are HTML files, simply place both on your desktop and open the parent, open_close_window.html from there and see how you can click the button to open the child window and then click the child's button to close itself by calling a close function in the parent. Odd, but that's how it's done!

Understanding ARIA Click Button to Show or Hide Content Example Code

Understanding ARIA

ARIA stands for "Accessible Rich Internet Applications". Also known as the WAI-ARIA standard, it is a standard developed to help coders to provide proper semantics for custom widgets and to make them accessible, usable, and interoperable with assistive technologies for people with disabilities. To be clear, ARIA doesn't add functionality to an object. It adds roles and states that assist in identifying the intent and state of an object. However, usually JavaScript code is still needed to add any dynamic action to that object. I state this clearly at the top of this post because at first, I was under the impression that ARIA also added certain functionalities to HTML objects and was seriously disappointed when I found out otherwise. For example, when ARIA is used on a button that hides and shows content in a div, it only defines the roles and states of the button and corresponding div. JavaScript is still needed to do that work of hiding and showing the div in question.

Example Code

Here is an example of correctly implementing ARIA controls when making a button that hides and shows a div on the click of your mouse. It also binds the space bar and enter key to the div as well, so pressing either of those keys toggles the visibility of the div as well. Without any further ado, the code:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Aria Examples</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<style>
div.topic {
    display: none;
    margin-bottom: 1em;
    padding: .25em;
    border: black thin solid;
    background-color: #EEEEFF;
    width: 40em;
}
</style>
</head>
<body>

<p class="button">
    <button id="button1" class="buttonControl" aria-controls="t1" aria-expanded="false"><span>Show</span> Topic 1</button>
</p>

<div id="t1" class="topic" role="region" tabindex="-1" >
    Topic 1 is all about being Topic 1 and may or may not have anything to do with other topics.
</div>

<script>
$(document).ready(function() {

   var hs1 = new hideShow('button1');
  // var hs2 = new hideShow('button2');
  // var hs3 = new hideShow('button3');
  // var hs4 = new hideShow('button4');
 
}); // end ready()

//
// function hideShow() is the constructor for a hideShow widget. it accepts the html ID of
// an element to attach to.
//
// @param(id string) id is the html ID of the element to attach to
//
// @return N/A
//
function hideShow(id) {

   this.$id = $('#' + id);
   this.$region = $('#' + this.$id.attr('aria-controls'));

   this.keys = {
               enter: 13,
               space: 32
               };

   this.toggleSpeed = 100;

   // bind handlers
   this.bindHandlers();

} // end hidShow() constructor

//
// Function bindHandlers() is a member function to bind event handlers to the hideShow region
//
// return N/A
//
hideShow.prototype.bindHandlers = function() {

   var thisObj = this;

   this.$id.click(function(e) {

      thisObj.toggleRegion();

      e.stopPropagation();
      return false;
   });
}

//
// Function toggleRegion() is a member function to toggle the display of the hideShow region
//
// return N/A
//
hideShow.prototype.toggleRegion = function() {

      var thisObj = this;

    // toggle the region
    this.$region.slideToggle(this.toggleSpeed, function() {

      if ($(this).attr('aria-expanded') == 'false') { // region is collapsed

        // update the aria-expanded attribute of the region
        $(this).attr('aria-expanded', 'true');

        // move focus to the region
        $(this).focus();

        // update the button label
        thisObj.$id.find('span').html('Hide');

      }
      else { // region is expanded

        // update the aria-expanded attribute of the region
        $(this).attr('aria-expanded', 'false');

        // update the button label
        thisObj.$id.find('span').html('Show');
      }
    });

} // end toggleRegion()
</script>
</body>
</html>

Thank you oaa-accessibility.org for providing me with enough knowledge to create and use the above example! They have the best example code for ARIA usage that I could find online after many Google searches. See their complete list of example ARIA examples at http://oaa-accessibility.org/

ARIA and WordPress

I noticed ARIA controls for the first time in the header.php file for my WordPress theme. I was trying to fix a mobile navigation menu and thought couldn't find the code that makes the menu appear on mobile devices when the button is clicked and thought ARIA had something to do with it. I was basically wrong. ARIA code was only present to mark the navigation menu and make it's role and states readily accessible. It is after all an accessibility feature.

Summary

So ARIA and the WAI-ARIA standard are used to enable more accessible HTML markup for disabled people. While it is a great initiative, it doesn't add much dynamic functionality to your HTML objects, JavaScript is still needed for that. ARIA combined with HTML, CSS and JavaScript can be used to make accessible web pages more user-friendly.

Get the Nth Weekday of Any Month and Year with JavaScript

In today's challenge for a client of mine, I had to write a JavaScript function that returns the Nth Weekday of any given month and year. For example it can tell you what the 1st Monday is in December, 2017. It can do past, present and future so if you needed to know the 4th Friday in August of 1910, this function can tell you. If you need to know what the second Sunday of January 2050 is going to be, this JavaScript function will tell you!

Without any further time wasting, here is the JavaScript code that can determine the first, second, third, fourth or even fifth Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday for any month and year you pass it:

JavaScript Code Returns Nth Weekday for any Given Month & Year:

<script>
/* JavaScript getMonthlyWeekday Function:
 * Written by Ian L. of Jafty.com
 *
 * Description:
 * Gets Nth weekday for given month/year. For example, it can give you the date of the first monday in January, 2017 or it could give you the third Friday of June, 1999. Can get up to the fifth weekday of any given month, but will return FALSE if there is no fifth day in the given month/year.
 *
 *
 * Parameters:
 *    n = 1-5 for first, second, third, fourth or fifth weekday of the month
 *    d = full spelled out weekday Monday-Friday
 *    m = Full spelled out month like June
 *    y = Four digit representation of the year like 2017
 *
 * Return Values:
 * returns 1-31 for the date of the queried month/year that the nth weekday falls on.
 * returns false if there isn't an nth weekday in the queried month/year
*/
function getMonthlyWeekday(n,d,m,y){
var targetDay, curDay=0, i=1, seekDay;
    if(d=="Sunday") seekDay = 0;
    if(d=="Monday") seekDay = 1;
    if(d=="Tuesday") seekDay = 2;
    if(d=="Wednesday") seekDay = 3;
    if(d=="Thursday") seekDay = 4;
    if(d=="Friday") seekDay = 5;
    if(d=="Saturday") seekDay = 6;
while(curDay < n && i < 31){
    targetDay = new Date(i++ + " "+m+" "+y);
    if(targetDay.getDay()==seekDay) curDay++;
}
if(curDay==n){
targetDay = targetDay.getDate();
return targetDay;
}else{return false;}
}//end getMonthlyWeekday JS function
</script>
<a href="JavaScript:var dy = getMonthlyWeekday(1,'Sunday','March', 2017);alert('1st Sunday in March, 2017 falls on March, '+dy);">Get first sunday in March, 2017</a><br />
<a href="JavaScript:var dy = getMonthlyWeekday(2,'Sunday','March', 2017);alert('2nd Sunday in March, 2017 falls on March, '+dy);">Get second sunday in March, 2017</a><br />
<a href="JavaScript:var dy = getMonthlyWeekday(5,'Sunday','March', 2017);alert('5th Sunday in March, 2017 falls on March, '+dy);">Get fifth sunday in March, 2017</a><br />
<a href="JavaScript:var dy = getMonthlyWeekday(4,'Friday','April', 2017);alert('4th Friday in April, 2017 falls on April, '+dy);">Get 4th Friday in April, 2017</a><br />
<a href="JavaScript:var dy = getMonthlyWeekday(5,'Monday','April', 2017);alert('5th Monday in April, 2017 falls on April, '+dy);">Get 5th Monday in April, 2017</a><br />
<a href="JavaScript:var dy = getMonthlyWeekday(3,'Wednesday','October', 1995);alert('3rd Wednesday in October, 1995 falls on October, '+dy);">Get 3rd Wednesday in October, 1995</a><br />
<a href="JavaScript:var dy = getMonthlyWeekday(4,'Wednesday','October', 1995);alert('4th Wednesday in October, 1995 falls on October, '+dy);">Get 4th Wednesday in October, 1995</a><br />
<a href="JavaScript:var dy = getMonthlyWeekday(4,'Wednesday','May', 1975);alert('4rd Wednesday in May, 1975 falls on May, '+dy);">Get 4th Wednesday in May, 1975</a><br />

Summary

That will do the job! All you have to do is copy and paste the above code in green into a blank text file and name it something like weekdays.html or test.html and open it in any web browser to test the code. Then feel free to alter it to fit your exact needs. Have fun!

 

 

 

How to Use jQuery UI Elements In a WordPress Plugin or Theme

Today I found myself once again needing to use jQuery in a new WordPress plugin I am developing for a client. I won't lie, I often dread having to use jQuery within WordPress. It has been getting easier however, especially since WordPress version 3.3.x when they made many of the jQuery UI libraries part of the WordPress core. The trick is knowing that and knowing how to use them! For example I didn't know about the jQuery UI libraries being part of the WP core until recently, so was just hacking my own jQuery into WordPress. The problem with hacking in a jQuery UI or any other jQuery code, is that it will usually break some other jQuery code in WordPress. Therefore I am putting together a quick reference guide on how to include jQuery and jQuery UI scripts in WordPress plugins and themes for my own reference and for other developers who can profit from this information.

First, here is a list of 35 jQueryUI elements already available within WordPress as of version 3.3.x:

Name: Enqueue Value: Dependency:
jQuery UI Core jquery-ui-core jquery
jQuery UI Widget jquery-ui-widget jquery
jQuery UI Accordion jquery-ui-accordion jquery
jQuery UI Autocomplete jquery-ui-autocomplete jquery
jQuery UI Button jquery-ui-button jquery
jQuery UI Datepicker jquery-ui-datepicker jquery
jQuery UI Dialog jquery-ui-dialog jquery
jQuery UI Draggable jquery-ui-draggable jquery
jQuery UI Droppable jquery-ui-droppable jquery
jQuery UI Menu jquery-ui-menu jquery
jQuery UI Mouse jquery-ui-mouse jquery
jQuery UI Position jquery-ui-position jquery
jQuery UI Progressbar jquery-ui-progressbar jquery
jQuery UI Selectable jquery-ui-selectable jquery
jQuery UI Resizable jquery-ui-resizable jquery
jQuery UI Selectmenu jquery-ui-selectmenu jquery
jQuery UI Sortable jquery-ui-sortable jquery
jQuery UI Slider jquery-ui-slider jquery
jQuery UI Spinner jquery-ui-spinner jquery
jQuery UI Tooltips jquery-ui-tooltip jquery
jQuery UI Tabs jquery-ui-tabs jquery
jQuery UI Effects jquery-effects-core jquery
jQuery UI Effects – Blind jquery-effects-blind jquery-effects-core
jQuery UI Effects – Bounce jquery-effects-bounce jquery-effects-core
jQuery UI Effects – Clip jquery-effects-clip jquery-effects-core
jQuery UI Effects – Drop jquery-effects-drop jquery-effects-core
jQuery UI Effects – Explode jquery-effects-explode jquery-effects-core
jQuery UI Effects – Fade jquery-effects-fade jquery-effects-core
jQuery UI Effects – Fold jquery-effects-fold jquery-effects-core
jQuery UI Effects – Highlight jquery-effects-highlight jquery-effects-core
jQuery UI Effects – Pulsate jquery-effects-pulsate jquery-effects-core
jQuery UI Effects – Scale jquery-effects-scale jquery-effects-core
jQuery UI Effects – Shake jquery-effects-shake jquery-effects-core
jQuery UI Effects – Slide jquery-effects-slide jquery-effects-core
jQuery UI Effects – Transfer jquery-effects-transfer jquery-effects-core

As you can see in the above table, the first 22 items in the list only require jQuery as a dependency. For those, you probably will only need to enqueue the value from the "Enqueue Value" column to make use of the library in your plugin or theme. You often will need to enqueue style for the jQuery library separately as well because as far as I know, WordPress doesn't include many of the styles yet. the last dozen or so in the above table all require jquery-effects-core, so to use those, I believe you'll need to enqueue that as well for them to work. For a complete list of other jQuery scripts that are already within the WordPress core, please visit the following codex page:

https://developer.wordpress.org/reference/functions/wp_enqueue_script/

That page also explains usage of the wp-enqueue-script function to  a degree, but not as detailed as my special-use case described here.

How to Enqueue jQuery UI Elements in WordPress Plugin or Theme

Next I'm explaining how to include a jQuery UI library into your own WordPress plugin or theme. If you're making a plugin, the code below will go into your plugin's main file and if you're working on a theme, then place the code below in the theme's functions.php file. In the following code examples, I'll demonstrate how to include both the jQuery UI element and the corresponding CSS file for using a datepicker in both the front-end and admin areas of WordPress. The code would be the same for any of the UI elements in the above table except that you would of course change the valuse to be enqueued for both the core jQuery file and the CSS file from googleapis.com.

PHP Code to use jQuery UI on the WordPress Front-End

function my_datepicker_function(){
//Enqueue date picker UI from WP core:
wp_enqueue_script('jquery-ui-datepicker');
//Enqueue the jQuery UI theme css file from google:
wp_enqueue_style('e2b-admin-ui-css','http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/themes/base/jquery-ui.css',false,"1.9.0",false);
}
add_action('wp_enqueue_scripts', 'my_datepicker_function');

How to add PHP Code to Use jQuery UI on the WordPress Admin or Back-End

The PHP code to include the same datepicker UI in a WordPress back-end, admin page is nearly the same. The only difference is the hook we use in the add_action line at the end of the code is different. For front-end use, we used the wp_enqueue_scripts hook, but for admin use, we will use the admin_enqueue_scripts hook instead. That's all folks!

Then simply include your HTML and  script tag wherever you want to use your datepicker in this case like so:

<div class="wrap">
<input type="text" class="datepicker" name="datepicker" value=""/>
</div>

<script>
jQuery(function() {
    jQuery( ".datepicker" ).datepicker({
        dateFormat : "dd-mm-yy"
    });
});
</script>

Summary

the above example code is just for datepicker UI, but can easily be manipulated for any of the jQuery UI elements in the above table, so experiment and find the one that works for you. You will often need to google the jQuery UI element's name and view an online demo of how it is used without WordPress to get exact code and then simply incorporate the above technique into what you learn. I did this with the sortable UI and it worked great. Good luck!

 

How to get Locations in a 50 Mile Radius with Google Maps API v.3

In this post, I will demonstrate how to make getting locations within a given radius simple. In order to make everyone understand, I will break it down into smaller, easy to read steps.

The Distance-Matrix

The key to creating a solution that gets all locations within a given distance radius is to use the Google Maps API Distance-Matrix. Let's examine a simple example request to the Distance-Matrix Json API:

Single Destination URL Example:

https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=44311&destinations=45735&key=Your_API_Key

copy and paste the above URL into a web browser and replace the text, Your_API_Key, with your google Maps V.3 API key. If you don't have an API key yet, they are surprisingly easy to obtain from https://developers.google.com/maps/web-services/

The Response:

The URL above will return a Json response of:

{
   "destination_addresses" : [ "Guysville, OH 45735, USA" ],
   "origin_addresses" : [ "Akron, OH 44311, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "166 mi",
                  "value" : 267653
               },
               "duration" : {
                  "text" : "2 hours 30 mins",
                  "value" : 8989
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Notice that I only used zip codes for orgin and destination in my example URL. You can use any acceptable address format instead of just a zip code of you like, but I find that for getting distances, zip codes work quite efficiently. Examples of acceptable addresses include:

  • Cleveland, OH
  • 593 Brown Street, Akron, Ohio
  • 44319
  • Akron, Ohio 4319
  • 593 Brown Street, Akron, Ohio 44311
  • USA
  • Amsterdam

Those are just a few acceptable addresses that could be used for either the destination or orgin parameters in the URL used for an API request to the Distance-Matrix.

 

Multiple Destination URL Example:

One thing that's important to know about the Distance-Matrix API is that there are limits on it's free usage. At the time of writing this post, the limits were 2500 elements per day. A single request may take up several elements however, so be careful. However it is much more practical to include several destination addresses in a single request because it will make your script run significantly quicker. Here is a simple example that will return a response with two destination distances using just zip codes for addresses again:

https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=44311&destinations=45735|44319&key=Your_API_Key

This the json response will include the distances for both zip codes or addresses passed in the URL. Here is the response from the above URL with two destinations:

{
   "destination_addresses" : [ "Guysville, OH 45735, USA", "Akron, OH 44319, USA" ],
   "origin_addresses" : [ "Akron, OH 44311, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "166 mi",
                  "value" : 267653
               },
               "duration" : {
                  "text" : "2 hours 30 mins",
                  "value" : 8989
               },
               "status" : "OK"
            },
            {
               "distance" : {
                  "text" : "8.9 mi",
                  "value" : 14385
               },
               "duration" : {
                  "text" : "14 mins",
                  "value" : 836
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Parsing Json data with PHP

The next task is to fetch a response from PHP and parse the Json data in your PHP code. Lets look at a practical example using our first URL example above that has a single zip code as the destination address and also a single zip code for the orgin. Here is the PHP code to make the request, get a Json response and parse the distance from that response:

<?php
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=44311&destinations=45735&key=Your-API-Key";

    //fetch json response from googleapis.com:
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = json_decode(curl_exec($ch), true);
    //If google responds with a status of OK
    //Extract the distance text:
    if($response['status'] == "OK"){
        $dist = $response['rows'][0]['elements'][0]['distance']['text'];
        echo "<p>Dist: $dist</p>";
    }
?>

Now lets have a look at how we would modify the above code for a request with two destination addresses instead of one:

<?php
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=44311&destinations=45735|44319&key=Your-API-Key";

    //fetch json response from googleapis.com:
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = json_decode(curl_exec($ch), true);
    //If google responds with a status of OK
    //Extract the distance text:
    if($response['status'] == "OK"){
        $dist = $response['rows'][0]['elements'][0]['distance']['text'];
        echo "<p>Dist: $dist</p>";
        $dist2 = $response['rows'][0]['elements'][1]['distance']['text'];
        echo "<p>Dist2: $dist2</p>";
    }
?>

If you insert your own API key in the above code and run it from your own server, the response would look like this:

Dist: 166 mi

Dist2: 8.9 mi

Notice the difference in the $dist and $dist2 variable values. The key of the elements is different. The first distance is stored in elements[0] while the second is stored in elements[1]. If we had three destinations in the request, the third would be in elements[2] and so on...

How to figure out the values

So, what if you want more than just distance from the returned json element? Lets examine the returned data and figure out how to get it into PHP variables. In the example code above, try placeing this code right after the line that reads "if($response['status'] == "OK"){" and it will show you what the PHP array looks like after the Json response was converted to a PHP object:

        echo "<pre>";
        print_r($response);
        echo "</pre>";

The above code inserted into the last code example would look like:

<?php
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=44311&destinations=45735|44319&key=Your-API-Key";

    //fetch json response from googleapis.com:
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = json_decode(curl_exec($ch), true);
    //If google responds with a status of OK
    //Extract the distance text:
    if($response['status'] == "OK"){
        echo "<pre>";
        print_r($response);
        echo "</pre>";
        $dist = $response['rows'][0]['elements'][0]['distance']['text'];
        echo "<p>Dist: $dist</p>";
        $dist2 = $response['rows'][0]['elements'][1]['distance']['text'];
        echo "<p>Dist2: $dist2</p>";
    }
?>

Again, replace "Your-API-Key" in the URL variable with your own key and run the code. You should see results like this:

Array
(
    [destination_addresses] => Array
        (
            [0] => Guysville, OH 45735, USA
            [1] => Akron, OH 44319, USA
        )

    [origin_addresses] => Array
        (
            [0] => Akron, OH 44311, USA
        )

    [rows] => Array
        (
            [0] => Array
                (
                    [elements] => Array
                        (
                            [0] => Array
                                (
                                    [distance] => Array
                                        (
                                            [text] => 166 mi
                                            [value] => 267653
                                        )

                                    [duration] => Array
                                        (
                                            [text] => 2 hours 30 mins
                                            [value] => 8989
                                        )

                                    [status] => OK
                                )

                            [1] => Array
                                (
                                    [distance] => Array
                                        (
                                            [text] => 8.9 mi
                                            [value] => 14385
                                        )

                                    [duration] => Array
                                        (
                                            [text] => 14 mins
                                            [value] => 836
                                        )

                                    [status] => OK
                                )

                        )

                )

        )

    [status] => OK
)

Dist: 166 mi

Dist2: 8.9 mi

First you see the array printed out from the response after it's converted from Json to a PHP array, then you see the two distances printed to the screen in the last two lines. Examine the array closely and you can figure out the correct keys to use to pick out specific values from the array in your PHP code.

More info on the Distance-Matrix can be found at https://developers.google.com/maps/documentation/distance-matrix/start

How to Make a Simple Pure JavaScript Popup Window

If you are a minimalist like me, you may appreciate this technique of making a simple JavaScript pop up window with nothing but HTML, CSS and JavaScript. It has no JQuery or other code other than those just mentioned.

See it Live

Here is a live version with just a little extra Style added:

http://jafty.com/pop.html

The Code

Now here is the simple code without much extra CSS style to keep it simple. If you copy and paste this into a blank HTML document, you will get a simple JavaScript working popup window:

<!DOCTYPE html>
<html>
<head>
<title>Pure JavaScript Popup</title>
</head>
<body>

<!--This is the popup code for when the div is clicked:-->
<script>
function iconPop(){
    document.getElementById('popcontent').innerHTML="You may click the X in the lower right corner to close this window or you may click outside of this window to close it as well.";
    document.getElementById('thepopup').style.display="block";
    document.getElementById('blackoutdiv').style.display="block";
}//end iconPop JS function

function iconUnPop(){
    document.getElementById('thepopup').style.display="none";
    document.getElementById('blackoutdiv').style.display="none";
}
</script>
<!--this is the blackout div that blacks out the rest of the page when popup is popped:-->
<div onclick="iconUnPop();" id="blackoutdiv" style="position:absolute; width:100%; height:100%; top:0px; left:0px;background-color:#222;opacity:0.6;z-index:9999;display:none"></div>

<!--this is the popup html:-->
<div id="thepopup" style="position:absolute; width:300px; height:150px; top:150px; left:50%; margin-left:-155px;border: 5px solid orange;background-color:white;z-index:99999;padding:15px;-webkit-border-radius:5px;border-radius:5px;display:none;"><span onclick="iconUnPop();" style="position:absolute;bottom:5px;right:5px;color:red;font-weight:bold;cursor:pointer" title="Close Window!">-X-</span><span id="popcontent"></span></div>
<!--End pop up code when icon's clicked-->

    
    <!--this is the div that when clicked, causes the popup window to appear:-->
    <div onclick="iconPop();" style="position:relative;top:75px;left:50%;margin-left:-170px;width:300px;height:200px;border:5px solid orange;-webkit-border-radius:5px;border-radius:5px;padding:30px;background-color:yellow;color:black">Click this div to open the Pure JavaScript Popup!</div>

</body>
</html>

Summary

That's really all there is to it. If you like the live version better, you can right click on the demo and select "view-source" and copy and paste that code into your own blank HTML document.

Building a Custom WordPress Navigation Menu Plugin

This is a semi-advanced WordPress tutorial so you should have a little bit of existing knowledge of WordPress if you want to be able to understand the concepts involved. I will try to make it as easy to follow as possible none-the-less.

We are just going to dive right in a create a new Plugin. I'll be calling the plugin Jafty-Nav, you can follow suit if you wish to keep things simple or give it your own name if you feel comfortable making such changes.

Create a New Plugin

<?php
/**
* Plugin Name: Jafty Top Nav Plugin
* Plugin URI: http://jafty.com/blog/?p=9813
* Description: A Plugin that adds a custom top navigation menu to WordPress.
* Version: 1.0
* Author: Ian L. of Jafty.com
* Author URI: http://jafty.com
* License: GPL2
*/

Register a New Menu Location with WordPress

Add this PHP code to your plugin file you created above:

<?php
add_action('after_setup_theme', 'register_jafty_menu');
function register_jafty_menu(){
  register_nav_menu('jafty-top-nav', __('Primary Jafty Menu', 'jafty-top-nav-plugin'));
}
?>

Now that is actually enough to create a simple plugin. The plugin will add a menu location to wp-admin and that's it, but we'll build on it after we install it. So go ahead and install the plugin by putting it into a folder named "jafty-top-nav-plugin" and naming the file "index.php". Then upload to your WordPress plugins directory. Activate the Jafty Top Nav Plugin then go to your admin and click on "Appearance/Menus" then select the "Manage Locations" tab and you'll see the new menu location your plugin as added to the admin like in the image below.

menuLOC

Placing a new top nav in your theme

The next task is to edit your current WordPress theme to work with the Jafty Top Nav Plugin. You'll need to create a new header file and edit your page, post and/or home page templates to contain your new top navigation menu. Here is how:

  1. Go into your current theme's folder and download a copy of the header.php file to your desktop and rename it header-jafty.php.
  2. open header-jafty.php in notepad and find the section that looks something like this:<nav id="site-navigation" class="main-navigation" role="navigation">
    <button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false"><?php esc_html_e( 'Primary Menu', 'outer-gain-dev' ); ?></button>
    <?php wp_nav_menu( array( 'theme_location' => 'menu-1', 'menu_id' => 'primary-menu' ) ); ?>
    </nav>
  3. Inside the code within the Nav tag in your header-jafty.php file, change the theme_location value to 'jafty-top-nav' and save the file.
  4. Now upload your header-jafty.php file to your active theme's folder.
  5. Next you'll want to add the new header to your template files, Some templates you might want to do this too are front-page.php, single.php, page.php and any custom page templates in your theme or child theme you might have. The process is very similar for adding the new header to any of the files, so I'll just demonstrate on the home page template file, front-page.php. Open the template file in your notepad and near the top of the code you should see something like this:
    get_header();
    or you may have something like this instead:
    get_template_part('templates/header.php');
    Regardless which you have, replace the line with:
    get_header('jafty');
    and that will call your new header.jafty.php template into the page template so your customized header will be shown.
  6. Save and upload your altered template file and repeat for all necessary page and post templates until you have your new top nav menu at the top of all desired pages and/or posts throughout your entire WordPress site.

Now that we have more control of it, let's customize that ugly top nav!

Customizing the WP Navigation Menu

It's time to get down and dirty with some real-world customization of the top navigation menu in WordPress. We are not just doing some simple CSS changes here, we are talking about a complete rewrite of the navigation system. This is why I went with a plugin for this. Now I had to find what WordPress core functions I could use to alter the menu completely. My goal is to make a menu similar to the one at Stripe.com, which is not a WordPress site by the way. I just love the dynamic drop downs that fade in and out and their use of icons in the sub-menu items. I'll get to how I duplicated all of that later on, first we need to know how to rebuild the entire menu structure because the stripe.com style menu is nothing like a standard WordPress menu. Here's what I figured out:

 

First we need to be able to retrieve our custom navigation links from the WordPress backend. Remember earlier we created a menu location? Well, we need to retrieve the menu assigned to that particular location in WordPress. Therefore the first thing we want to do is make sure there is a menu assigned to the "Primary Jafty Menu". You could pick one from the drop down, but we want to make a new one that is sure to have both main menu items and sub menu items so we can adequately test our menu when it's complete. Therefore we locate the "Primary Jafty Menu" and click the link to the right of it that reads "Use New Menu" as I've circled in red in the below image:

menuLOC2

When creating the new Primary Jafty Menu, give it a name of "Jafty 1". It's best to do everything exactly as I have done just to be sure you don't have any conflicts. You can always change names and such after you have a completed working plugin. When creating the menu, make sure to add at least 2 main menu items with at least 2 sub menu items each so we can test the drop down effects. Here is an image of the one I made for testing. If you don't have enough pages or posts to make that many links, don't worry, just use two real links for the main menu items and click on "custom links" and create outside links for all of your sub menu items as I have done in the below image:

menustructure

In the above image, "site settings" and "Hello world!" represent our two main menu items and the sub links rest below them indented to show their sub-link status. Notice I have "Primary Jafty Menu" checked under "Menu Setings" too. Once you have your menu, be sure you save it. Now we can return to developing our plugin!

Retrieve Menu and Sub Menu Items from WordPress Admin

It is time to develop some custom WordPress code to extract out menu items and sub-menu items from the database. Lucky for us, WordPress has some built-in core functions to assist us. Here is the code I come up with to extract all menu and sub-menu items for the "Jafty Primary Menu" from the database to display them on the front-end:

<?php
      $menuLocations = get_nav_menu_locations(); // Get nav locations
      $menuID = $menuLocations['jafty-top-nav']; //menu assigned to Jafty Primary Menu
      $theNav = wp_get_nav_menu_items($menuID);
                
                    foreach ($theNav as $navItem) {
                        //get the url for the link:
                        $navURL = $navItem->url;
                        //get the nav link text/title:
                        $navTXT = $navItem->title;
                        //Get the nav link's ID:
                        $navID = $navItem->ID;
                        //Get menu item parent(will be 0 if main link or parent ID if it's a sub link):
                        $navParent  = $navItem->menu_item_parent;
                        echo "ID: $navID, $navTXT, $navParent, $navURL<br />";
                    //echo '<li class="has-dropdown gallery" data-content="about"><a href="'.$navURL.'" title="'.$navItem->title.'">'.$navTXT.'</a></li>';
                    }
 ?>

The above code will go in out header file named header-jafty.php. Lets examine the code so you understand what it does.

The first line:

$menuLocations = get_nav_menu_locations(); // Get nav locations

as the comment says afterwards, it gets the navigation menu locations stored in WordPress. We added one of these in the beginning of the tutorial using the register_nav_menu function.

The second line reads:

$menuID = $menuLocations['jafty-top-nav']; //menu assigned to 'Primary Jafty Menu'

This line fetches the ID of the menu currently assigned to the menu location we created in the plugin file, "Primary Jafty Menu". We then use the id in the next line that reads:

$theNav = wp_get_nav_menu_items($menuID);

We now have a WordPress menu object stored in $theNav. If you do a print_r($theNav) command in PHP, you would see that the menu object holds all sorts of information about the menu we created earlier. However, we only need four key pieces of information from the menu object. We need to get:

  1. The Link URL
  2. The Link Text
  3. The Link ID
  4. The Link's Parent ID in case it is a sub-menu item.

We can get the four pieces of information we need using a foreach loop on the $theNav object like so:

     foreach ($theNav as $navItem) {
                        //get the url for the link:
                        $navURL = $navItem->url;
                        //get the nav link text/title:
                        $navTXT = $navItem->title;
                        //Get the nav link's ID:
                        $navID = $navItem->ID;
                        //Get menu item parent(will be 0 if main link or parent ID if it's a sub link):
                        $navParent  = $navItem->menu_item_parent;
                        echo "ID: $navID, $navTXT, $navParent, $navURL<br />";
                    //echo '<li class="has-dropdown gallery" data-content="about"><a href="'.$navURL.'" title="'.$navItem->title.'">'.$navTXT.'</a></li>';
                    }

We now have all the information we need about the menu items after running the above foreach loop on the menu object. We have the link text, URL, ID and Parent ID. It's important to note that the parent ID will always be 0 if the link is a main menu item and we can determine if the link is a sub-menu item if the parent ID is anything other than zero. Then we know which link to put the sub-link under by matching the sub-link's parent ID to the ID of the main link item. Pretty simply really, once you get accustomed to it.

Now we need to open our header-jafty.php file and find the line that reads something similar to:

<?php wp_nav_menu( array( 'theme_location' => 'jafty-top-nav', 'menu_id' => 'primary-menu' ) ); ?>

And replace it with the code we wrote above:

<?php
$menuLocations = get_nav_menu_locations(); // Get nav locations
$menuID = $menuLocations['jafty-top-nav']; // Get the *primary* menu ID
$theNav = wp_get_nav_menu_items($menuID);

foreach ($theNav as $navItem) {
//get the url for the link:
$navURL = $navItem->url;
//get the nav link text/title:
$navTXT = $navItem->title;
//Get the nav link's ID:
$navID = $navItem->ID;
//Get menu item parent(will be 0 if main link or parent ID if it's a sub link):
$navParent  = $navItem->menu_item_parent;
echo "ID: $navID, $navTXT, $navParent, $navURL<br />";
//echo '<li class="has-dropdown gallery" data-content="about"><a href="'.$navURL.'" title="'.$navItem->title.'">'.$navTXT.'</a></li>';
}
?>

Now save your header-jafty.php file and upload it to your active theme's folder and refresh your home page. You should see the following information printed in the header area of your site instead of a top nav now:

ID: 47, Site Settings, 0, http://dev.outergain.com/site-settings/
ID: 49, Jafty Interactive, 47, http://jafty.com
ID: 50, Jafty Blog, 47, http://jafty.com/blog
ID: 48, Hello world!, 0, http://dev.outergain.com/2016/12/30/hello-world/
ID: 51, Yahoo Search, 48, http://yahoo.com
ID: 52, Google Search, 48, http://google.com

As you can see my site returned 6 lines of text in the header, one for each of the two main menu items and one for each of the four sub-menu items in the menu I created in wp-admin. Each of the lines above contains the main ID first, followed by the link text, then the parent ID and finally the link text. I highlighted the parent IDs in blue so you can see how the two main menu items have a parent ID of zero while the other four have parent IDs equal to the two main menu items with zero for parent ID. Make sense? I hope so:-)

For all you professional WordPress plugin developers, I can probably stop there. Now you have enough to make your own custom top navigation menu for your WordPress theme. You clearly don't need to do this as a plugin, in fact, it would normally done by adding the plugin code to functions.php in the current theme instead. I am making it a plugin just as a learning exercise.

You can use the information it printed in your header to figure out how to add in the HTML and CSS for any type of custom nav you desire, or you can read on to see how I recreated the stripe.com-like top nav for one of my clients.

Make a Static Top Navigation Menu as a Demo

Before we go about coding the menu into WordPress, I like to create a static version first. I created mine based on looking at the top nav found on Stripe.com. You can click the link to see what I mean. I didn't copy it by any means, but I did use it as a model for creating a similar one with similar transition effects. In the static demo, I didn't create great detail in the drop downs. Instead I concentrated on getting the transition effects and infrastructure perfect. I can worry about making the content of the dropdown boxes look pretty when I code it into the actual WordPress site. Here is my static demo: http://jafty.com/nav_demo

I won't post all of the code to my static navigation menu demo here but you may feel free to use the link provided and use your browser's view source option to see how I made it and copy it if you so desire.

 

 

 

wp_redirect Causing Page Isn’t Redirecting Properly Error

I was working on a client's WordPress website today and had to do a redirect after successful login to his WordPress site. I tried to use wp_redirect with several different hooks including init, wp, wp_login, wp_redirect....etc. and none worked. I kept getting an error in Firefox that looked like this saying "The page isn't redirecting properly....Firefox has detected that the server us redirecting the request for this address in a way that will never complete:

redirecterr

The Solution

So, in short Here is my solution. While I'm sure there may be another better way, this is the only one I found after two hours of trying to use wp_redirect. I simply used this line in place of where I would normally use wp_redirect:

echo "<script>document.location = '/my-account/';</script>";

So I essentially insert a JavaScript redirect into the page using PHP. Hackish? Yes, but it works and hopefully this post will save someone hours of wasted time trying to get wp_redirect to work!

 

You Can Now Contribute Web Development Content

Jafty Interactive Web Development has decided to start accepting user contributed blog posts! You can now submit any post that is related to out blog theme of web development and it will be published after admin moderation. As long as it is on topic and I think it improves the quality of my blog, it will probably be published. Some topics I would like to encourage users to submit posts about include:

  • PHP
  • JavaScript
  • HTML
  • XML
  • CSS
  • Search Engine Optimization/SEO
  • Freelancing as a web developer
  • Freelance writing
  • working from home
  • Laravel
  • WordPress
  • C Languages
  • Java
  • ASP.net
  • JQUERY
  • Ruby on rails
  • MySQL Database
  • SQL
  • PHP and MySQL
  • Remote server administration
  • Linux Command Line
  • Linux and Windows Servers
  • MAC and web development
  • PC vs MAC
  • Mobile Development
  • Mobile website optimization
  • PERL
  • AJAX
  • Adwords
  • CURL
  • Graphics
  • anything else related to web development!

That's just a list to fuel your mind. Feel free to submit any related topic. I will accept anything related to web development. I'm looking forward to some great blog posts! - Ian L.

Click Here to Sign Up and Begin Writing!

 

CodeLobster All-in-One Coding Software

CodeLobster PHP Edition Software Review

Written by Ian Lincicome of Jafty Interactive Web Development - Jafty.com

For the past couple of weeks, I have been evaluating CodeLobster's latest release of "CodeLobster PHP Edition" which I'll refer to as simply "CodeLobster" from here on out in this review. The current edition at the time of writing this review was CodeLobster PHP Edition Professional Version 5.4. I am reviewing CodeLobster because I am looking for a tool I can use for my web development business, Jafty Interactive Web Development. Also I was given a break on purchasing the pro version of CodeLobster in exchange for writing a product review on my site, Jafty.com. Please note that I am under no obligation to write a positive review. I will be as brutally honest as ever, I assure you. This review will include both the pros and cons of using CodeLobster rather than a one-sided review like many company's probably hire writers to write. In fact, if that was my intention, I wouldn't have mentioned that the someone had asked me to write this review. My ulterior motive for writing the review is to find the perfect program to do my work for my business. I am also evaluating other products as well because I want to work with the best.

I'm looking for an application that will allow me to seamlessly edit several types of code on several different servers without having to use a separate code editor, FTP program, web browser and Language reference material. To this date, I have been using three separate applications to accomplish my day-to-day work. I used FileZilla to copy files from a client's web server to my desktop. I used Notepad++ to edit the code files. Finally, before using FileZilla again to upload the files back to the client's server, I viewed the file in Firefox to see how it looks in a browser. That is if it is not a server-side language like PHP which I use the most. If I had to edit a PHP file, I had yet another couple of steps to perform because I'd have to upload the file to the server to view it and then repeat the whole entire process again if I had more changes to make to get it perfect. So I used FileZilla, Notepad++ and Firefox mostly up until now. I figure I could probably almost double my productivity with one good tool that does it all.

Technologies CodeLobster Supports

CodeLobster supports a wide range of technologies including:

  • PHP
  • HTML
  • JavaScript
  • CSS
  • SQL
  • MySQL
  • Version control systems such as SVN, Git etc.
  • CakePHP
  • CodeIgniter
  • WordPress
  • Drupal
  • Joomla
  • Facebook
  • jQuery
  • Smarty
  • Symfony
  • Yii

CodeLobster also has a very wide assortment of features including all the standard components you would expect in a code editor and many extras. I found a helpful built-in Help feature that also links to online help if you can't find what you need in the built-in documentation. The online documentation is surprisingly complete for a newer product.

Installing CodeLobster

The installation went smoothly and was very easy and comprehensive. Simply download and click the set up file and the installer will guide you through the simple set up process. Here is the Download Link: http://www.codelobster.com/download.html

When I first installed CodeLobster, it allowed me to select what languages/technologies I wanted to install. I only deselected two that I knew for sure I would most likely never use. I figured if there was even a small chance that I might use one of the items listed, then I should leave it checked. That way I will be prepared in case I need that particular technology in the future.

Pros and Cons

Once I began using CodeLobster I noticed both good and bad points regarding the program. I loved how versatile the program was right out of the box. I did not like the way the word wrap feature worked(View/Word Wrap). It breaks up words rather than splitting lines by the nearest space. I'd prefer it to not break up words at all or at least do so in a more logical manner(by syllables with hyphens for example). From what I understand from reading the forums and talking with my contact, CodeLobster plans to add an option between soft and hard word-wrap. Hard wrap is how it is now and soft wrap would be a word-wrap technique that doesn't break up words. I do hope they add it soon because it was one of the of the first things I noticed.

One of the first features I noticed and liked was the completely configurable hot-keys. You can configure any hot-key by going to Tools/Preferences/IDE/Hot keys. Another nice feature is the Find and Replace feature that is very much like that of Notepad++ including regular expression search and the ability to search and replace text in files, folders and sub-folders. This can be a huge time-saver for coders.

One of the first things I noticed and did not like was the lack of a decent spell checker. I know notepad++ has the option as a plugin, but not as a built-in feature. Either way would be great, but I think it should be a standard built-in feature. I realize that auto-complete helps with this, but not if you are writing a plain text file such as I am doing right now while writing this review. I talked to my contact at CodeLobster Software about this and he assured me that they plan to add a robust spell-checking feature in the near future. He mentioned that they plan on making several additions to the software and will be releasing future editions with new features and improvements ASAP. So, while CodeLobster may not have everything I would like it to have at the moment, I was assured that they are heading in the right direction with future expansion plans.

Another nice feature I also noticed right away was CodeLobster's tool bars. The tool bars are completely configurable and have a nice drag and drop feature to move tool bar items around as you please. The same can be said for the man different windows that can be added or removed from the work area.

CodeLobster is a code editor first & foremost and it does a wonderful job at editing PHP code which is my code of choice. If you are looking for a word processor, CodeLobster probably won't fit the bill, but it is a very robust code editor that can handle all of the languages I use for web development and several others.

CodeLobster's plugin ability is great to have in a code editing program. The pro version of CodeLobster comes with many plugins that the free version does not include from what I understand, so I think the pro version is definitely worth the cost for those of you who work with frameworks such as WordPress, Joomla, CakePHP, CodeIgniter, etc. I currently own the Pro version and I am happy with its performance so far and will be much happier once some of the additions are made in the near future.

Even the free version would be great for coders who use many different coding languages regularly but don't need the extra plugin abilities that require the pro version. As a full-time web developer, I mostly use PHP, HTML, CSS, JavaScript, WordPress and MySQL. I also occasionally use Joomla, XML, Perl, Python, Drupal, Smarty, Laravel, CakePHP and others, so I require the Pro version of CodeLobster myself. If you only use the most common languages such as PHP, HTML, CSS and JavaScript, you can probably do fine with the free version. Some of the things I require the Pro version for include WordPress support, Smarty, Laravel and CakePHP. Honestly there are to many features to list here. You should visit their web page at http://www.codelobster.com/details_phped.html to figure out which version is best for you. They also have a Lite version which you can read about on their site since I won't be covering CodeLobster Lite here.

As I continue to evaluate the software I am finding there are more and more features that I like. As a web developer, I need a tool that allows me to quickly edit code, test it and upload it to the client's server. So far, CodeLobster seems to be meeting my three main requirements quite well in most cases.

FTP Feature

CodeLobster's FTP ability is a very powerful feature. The FTP feature allows you to set up as many FTP connections as you need. I was able to copy all of my client's FTP connections from FileZilla into CodeLobster. Now I am able to click on a connection, edit a server file, preview it and upload it back to the server seamlessly from within a single application! This is huge for me because I used to use at least three different applications to do the same thing without CodeLobster. I can see that my work will get done a lot faster by using CodeLobster. In fact, I am already getting work done faster after only two days of using it.

The FTP feature is very functional, but for a guy like me who hates to read instructions, it took a little bit of fooling around using trial and error methods to get it set up for the first time with all of my client's 20+ FTP connections and configuring basic settings. Everything I needed to accomplish my FTP tasks is in CodeLobster, but the FTP system does need some improvements. For example it gave me trouble when trying to connect to a SFTP connection. It worked great with all non-secure FTP connections however. As luck would have it, out of over 20 current clients I work with, only one uses SFTP rather than FTP, so I am unable to test it on other secure SFTP servers to see if the problem is just with this one server or not. Unfortunately this is one of my regular clients so it is going to be a problem for me. It did connect using SFTP, but had issues when trying to edit files on the server which I was able to do fine with regular FTP connections. I did bring this issue to the attention of my CodeLobster contact however and he assures me it will be looked into ASAP.

Regarding the GUI set-up for FTP, in my personal opinion, the way the windows are organized in the work area could have been done a little better. For example, when I use FTP, I have to go to Tools/FTP to open the explorer window that lists FTP connections. That alone will allow you to open your FTP connection but won't allow you to see what's going on. If there was an error and the only window you had open in your work area was the explorer window, you wouldn't see that error. This is where I think it could have been done better. I would have programmed it so that when you open the FTP window, the output window opens along with it, right above it, similar to how FileZilla allows you to view console output. Of course this is just my opinion, it may not bother others and actually I am starting to get used to it so it doesn't bother me as much as time passes.

Search Features

The "Find in Files"(Search/Find in Files...) feature is great for finding text in open files. It could be improved to allow file search on the local directory tree files as well, but it is sufficient the way it is. Also I love the regular expression search as I mentioned earlier.

Also, I often use the incremental search feature when I edit code. While I am glad it has this feature, a small nuisance for me is that the incremental search box is not persistent across different views. I think it would be nice if the incremental search box would stay at the bottom of all view tabs once it is opened. I don't think it should close unless you manually close it. Again, this is just my preference, not a bug.

Nice-to-Have Features

One more thing I liked while test driving CodeLobster is that when editing .html and .css files I could hover over class names in the HTML or CSS code and it would show me the associated style declaration. Also when hovering over items in a .css file, it shows me information regarding the browser compatibility of the CSS code.

The HTML preview feature works very well. It is a built-in browser that shows the results of your code live without having to open a separate browser window. All you do is click on the "preview" tab. I did notice that sometimes you have to hit the refresh button to see your changes, but that is to be expected.

I also enjoyed the code formatting features very much. I tested them on an HTML file that I copied from an online web page. At first the HTML code was ran all together with no line breaks or indents. I simply went to the tool bar and clicked "Tools/Code Format/Format" and it formatted it perfectly. I am sure it will work with other supported languages equally well.

When you double-click on a variable name in the PHP editor, it highlights the variable and the dollar sign, so you can copy the whole thing and paste or search for it easily. Notepad++ wouldn't include the dollar sign and it was a bother to me.

CodeLobster has what they call a "Map" feature(View/Windows/Map) that I've never seen before. It is basically a small window with a tiny view of the document you're working on. It allows you to click anywhere in the Map to quickly jump to a section of the file that you need to work on. It is a great feature for working with large files.

Conclusion

I have concluded that CodeLobster will indeed fill a need in my current web development process. It is not yet developed enough to be the only tool I use simply because of that one SFTP connection it will not work correctly with. However I found that I can combine it with another tool, CyberDuck, as a work-around until the developers of CodeLobster work out the final kinks in the software and add some more nice-to-have type features such as spell-check and . In the end it still gets a thumbs up for all the wonderful features it has and for its robustness in general. Eventually I believe it will make the perfect all-in-one coding tool for my company. The other contender for my new all-in-one coding tool was CyberDuck and I can honestly say that CodeLobster has much more potential. CyberDuck is also in its early stages of development and it needs several improvements to be truly useful. CyberDuck fails in comparison to CodeLobster when it comes to Features. CodeLobster is truly made to be an all-in-one coding solution while CyberDuck is missing many of the necessary features to be a real competitor.

If you are interested in how I combined CodeLobster with CyberDuck to make up for CodeLobster's short-coming when connecting by SFTP, I'll quickly go over how to do it. Create a bookmark(that's what CyberDuck calls their FTP/SFTP connections) in CyberDuck to the SFTP server. CyberDuck allows you to set it up so you can use your own code editor with it in a way that allows you to click on a file from a remote server and open it in that editor. Then when you save it in that editor(CodeLobster), it saves it to the server. That way I still have a seamless process even though I have to combine two tools to get what I truly want.

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. 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. 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).

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.

 

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>