Friday, August 9, 2013

jQuery - Selecting HTML Elements Using ID or Class Name

Learn how to easily select HTML elements using jQuery. You will also see the difference between traditional JavaScript and jQuery code.
(jQuery version 1.9.1 was used in this video)


Tuesday, February 12, 2013

Get URL Variables With JavaScript


As most of you probably know, the GET method is a common way for PHP websites to pass nonsensitive information between pages. At some point you may want to access this information dynamically using JavaScript. Luckily, accessing URL variables is rather simple and I will cover the process step by step below.


1. The first thing we need to do is create a demo URL that is using the GET method to test our script.


http://www.procureeminence.com/?title=JoeDirt&keyphrase=Classy



2. Next we can create a blank JavaScript function that will eventually be able to access the URL variables. Let's call the function "GetUrlValue()". We also want the ability to pass the desired URL variable name into the function so let's add the variable "VarSearch" to capture this data.


function GetUrlValue(VarSearch){

}



3. Next we need to get the "Query String". To do this we call the "window" object, access the location object within the window object and then access the search property. This will return a string containing "?title=Classy&keyphrase=NotJoeDirt" which is great except we don't need the "?".


function GetUrlValue(VarSearch){
    window.location.search;
}


      


4. To remove the "?", let's add the "substring()" method and remove the first character by passing 1 as the parameter.


function GetUrlValue(VarSearch){
    window.location.search.substring(1);
}



5. Create a variable called "SearchString" to store the query string.


function GetUrlValue(VarSearch){
    var SearchString = window.location.search.substring(1);
}



6. Now we will split the data up into individual variables (key-value pairs) and store it in an array called "VariableArray". To divide the variables we will use the "split()" method and specify that we want to split the string at every "&" character.


function GetUrlValue(VarSearch){
    var SearchString = window.location.search.substring(1);
    var VariableArray = SearchString.split('&');
}





7. Once we have the array of variables we need to create a "for" loop to scan for the desired variable. Since we are scanning through an array we need the var i to start at 0 because arrays are indexed starting at 0. "i" will be used to access the appropriate array element based on the loop iteration. Next we get the number of array elements stored in "VariableArray" by accessing the "length" property and make sure "i" doesn't reach that value. In our case "VariableArray.length" will equal 2 so the for loop will complete two cycles, once with i=0 and once with i=1 and on the third cycle i will become equal to "VariableArray.length" making the loop stop before the internal code is executed. To make "i" increase by 1 on each cycle we will add "i++" as the third parameter.


function GetUrlValue(VarSearch){
    var SearchString = window.location.search.substring(1);
    var VariableArray = SearchString.split('&');
    for(var i = 0; i < VariableArray.length; i++){

    }
}


8. Now that the for loop is set up we can add the search code. In order to search for the URL variable name we first need to split the key-value pair into another array. Add an array called "KeyValuePair" to store the key-value data from the previous array. To do this lets type the previous array name "VariableArray" and use the "i" variable to select a different array index on each cycle, which should look like this; "VariableArray[i]". Now that the index will be selected dynamically, we can use the "split()" method to separate the data into the new array. We must split the data based on the "=" character by passing it as a parameter; split('='). Please note that on each loop the previous data in the "KeyValuePair" will be overwritten by new data.


function GetUrlValue(VarSearch){
    var SearchString = window.location.search.substring(1);
    var VariableArray = SearchString.split('&');
    for(var i = 0; i < VariableArray.length; i++){
        var KeyValuePair = VariableArray[i].split('=');
    }
}


9. Since the key (aka URL variable name) will always be stored in index 0 of "KeyValuePair" we can use an
"if" statement to check for the matching URL variable name. Add "KeyValuePair" index 0 (KeyValuePair[0]) to the parameter and see if it's equal too (==) the variable name we had passed into the "GetUrlValue()" function, which was stored in the "VarSearch" variable. If the values match we want to return the current value of the key-value pair which will be in index 1 "KeyValuePair[1]". Once the return statement is called, the function will stop and the selected value will be returned. If no match is found the function will execute all the code contained within it and return the value of "undefined". At this point the function is finished and can be seen in its entirety below.

function GetUrlValue(VarSearch){
    var SearchString = window.location.search.substring(1);
    var VariableArray = SearchString.split('&');
    for(var i = 0; i < VariableArray.length; i++){
        var KeyValuePair = VariableArray[i].split('=');
        if(KeyValuePair[0] == VarSearch){
            return KeyValuePair[1];
        }
    }
}

10. To test out the function let's create an alert message that will display the value of our request URL variable. Please see the examples below:

//Alert the value of title
alert(GetUrlValue('title'));
     The output should be "JoeDirt"

//Alert the value of keyphrase
alert(GetUrlValue('keyphrase'));
      The output should be "Classy"

//Alert the value of random
alert(GetUrlValue('random'));
     The output should be "undefined"



Congrats! You have just made a simple function that retrieves URL variables and their values. I hope you enjoyed this tutorial and I look forward to all the comments/suggestions! For all source code, demos and reference material please use the links below.


Resources


References

Tuesday, January 8, 2013

JavaScript Image Loader (V1.8.2013)

Creating an Image Loader Using JavaScript

Many modern web apps use custom scripts that load all assets (images, files, external scripts... etc.) prior to calling the main application function. The purpose of a loader script is to prevent errors caused by a program that tries to manipulate assets before they are fulled downloaded. Unfortunately there aren't many tutorials available for this subject so I've created this post to show you how to create a simple loader script. This example is specifically designed for images but the basic principles will apply to the other asset types.

Click Here To View The Image Loader Demo

Before looking at any detailed code lets break down the process step by step.
  1. A visitor will enter our website/web app address into a browser.
  2. The page will begin to load.
  3. Once the page has finished loading it will call a function called 'loadImages()' that initiates the image loading process.
  4. loadImages() will cycle through a list of image links one at a time.
  5. Each image link will be allocated to a new image object and the new object will have a function assigned to each of the following events: onload, onerror and onabort.
  6. As each image loads or fails it will call the function 'calculateStatus()'. This function counts all images that have loaded/failed and calculates the width of a div element based on the percentage of completeness. Once the function detects that 100% of the images have loaded and/or failed it will call the next function that the website/web app requires, in our case it's just an alert function that tells us the images have loaded.
Now that we have discussed the basic process we can begin writing the loader script. 

1. The first thing we need to do is create a new HTML5 document as shown below:

<!DOCTYPE html>
<html>
<head>
<title>Image Loader Script</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
</head>
<body>

</body>
</html>

2. Create the loader status bar by nesting two div elements within the body element. The outside div will be the red bar and the inner div will be the green "status" bar. Set the outer div id to "LoadBarBackground" and set the inner div id to "LoadBar".

<div id="LoadBarBackground">
<div id="LoadBar"></div>
</div>

3. Next we need to create the CSS styles in the head element. (At this point if we load the page in a browser we should see a thin red loading bar.)

<style>
#LoadBarBackground{
width:300px;
height:10px;
padding:0px;
margin:0px;
background-color:red;
border-radius:10px;
}
#LoadBar{
width:0px;
height:10px;
padding:0px;
margin:0px;
background-color:green;
border-radius:10px;
}
</style>


4. Now we are ready to insert the script tag into the head element and set the global variables. Please refer to the comments in the code for a more detailed explanation.


<script>
//Set global variables
//Create global img array
var img = new Array();
//Create global variable that will count the total number of images loaded
var ImageLoadCount=0;
//Create global array of image URLs to load
//Replace all image URLs with your own and add more as necessary
var ImageLinkArray=[
'http://img.timeinc.net/time/photoessays/2008/trees/franklin_trees_01.jpg',
'http://www.dailygalaxy.com/photos/uncategorized/2007/10/17/trees_2.jpg',
'http://www.redorbit.com/media/uploads/2012/12/TreesDeclining_120712-617x416.jpg',
'http://www.thisiscolossal.com/wp-content/uploads/2012/01/tree-2.jpg',
'http://www.onearth.org/files/onearth/article_images/08spr_trees_01_h_feature.jpg',
'http://www.ces.ncsu.edu/fletcher/programs/xmas/images/fawn-trees-bryandavis.jpg',
'http://natureblognetwork.com/blog/wp-content/uploads/2010/01/042907_trees_1.jpg'
];
</script>


5. The next step is to create the imageLoader() function and place it directly after the ImageLinkArray within the script tag. Again, please refer to the comments in the code for a more detailed explanation.


function loadImages(){
//Loop through each image link and create an image reference to each
for(i=0;i<ImageLinkArray.length;i++){
//Create a new image object
img[i]=new Image();
//Set the currently selected link as the image source for the new object
if(ImageLinkArray[i] == '' || ImageLinkArray[i] == 'undefined'){
               //Set source to fake url if array index was left blank to force img[i].onerror event
img[i].src='eRroR666.jpg';
}else{
img[i].src=ImageLinkArray[i];
}
//Attach function to onload event for each image
img[i].onload=function(){
//Add one to the total image count now that the image has loaded
calculateStatus();
}
//Attach function to onerror event for each image
img[i].onerror=function(){
//Add one to the total image count now that we know the image can't be loaded
calculateStatus();
alert('Image could not load.');
}
//Attach function to onabort event for each image
img[i].onabort=function(){
//Add one to the total image count now that we know the image was aborted
calculateStatus();
alert('Image load was aborted.');
}
}
}



6. Create the final function that calculates the percentage of completeness and adjusts the "LoadBar" div accordingly. This function will also call the next function in the application or in our case, an alert message.


function calculateStatus(){
//Add one to the total image count now that this image has loaded
ImageLoadCount++;
     //Get the current width of the LoadBarBackground div
     var LBBWidth = document.getElementById('LoadBarBackground').offsetWidth;
//Adjust the loader bar according to how many images have loaded so far
document.getElementById('LoadBar').style.width=((LBBWidth/ImageLinkArray.length)*(ImageLoadCount)) + "px";
//Check to see if all images have load
if(ImageLoadCount == ImageLinkArray.length){//If true, all images have been loaded
//Insert your next function call in place of this alert message
setTimeout(function(){alert("All images have loaded!");},3);
           //Timer is used to ensure JavaScript DOM manipulation completes before next function call
}
      //Update the total number images loaded in the global variable
return ImageLoadCount;
}


7. Lastly we need to modify the opening body tag by assigning the loadImages() function to the onload event. This will trigger the image loader functions once the page has finished loading.



<body onload="loadImages()">



8. Save the html file and load it in a browser. You should see the green bar gradually fill in the red bar from left to right as the images load. Once the loading has completed you will get an alert message saying "All images have loaded!".



Congratulations, you have created your first image loader script! I hope you enjoyed this tutorial and I look forward to all the comments/suggestions! For all source code, demos and reference material please use the links below.


Resources



References







Monday, January 7, 2013

IE8 getElementsByClassName() Error


IE8 Element Selection by Class Name Fix

As some of you may have found out Internet Explorer 8 doesn't support the getElementsByClassName() JavaScript method. If you try using this method you will get the following error:
"Object doesn't support this property or method"

To get around this all you need to do is use the querySelectorAll() method which comes standard with JavaScript. If the jQuery library is installed on your site you can also use the $('') selector function to fix the compatibility issue. jQuery will try using getElementsByClassName() first if the browser supports it, if not jQuery uses the querySelectorAll() method. See solutions below:

Original Code Not Compatible With IE8
var ObjRef = document.getElementsByClassName('ExampleClass');

New Code
var ObjRef = document.querySelectorAll('.ExampleClass');

jQuery Code
var ObjRef = $('.ExampleClass');


Note: Don't forget to enter the appropriate CSS selectors when using the querySelectorAll() method or the jQuery $('') function. For more information on CSS selectors click on the W3Schools link below.

References





Blog Purpose & Intended Audience

Purpose:
The purpose of this blog is to help JavaScript/ECMAScript users become more productive by sharing tips and tricks as well as outside reading material. I'll cover several aspects of js libraries, cross-browser compatibility, naming conventions and DOM manipulation. Each blog post will include links to reference material, code examples and screenshots whenever possible.

Audience:
The content provided assumes that the viewer has a basic understanding of HTML5, CSS3 and JavaScript.

Author:
Michael Bigelow
Procure Eminence
www.procureeminence.com