Arrays

Javascript Arrays are an object that permits you to store multiple values into a collection for easy reference. For example, if you wanted to track a user’s position position over some time, you could insert the x and y values into an array. Arrays are more than just the example of x and y values though.

Let’s say we are building a calculator. Initially, we might think that we only need to variables. We need one for the first number before the operator is pressed and another one after. Congratulations on us being super static. Maybe we now want to be able to add more than just 2 values before calculating the sum. We should have used an array from the very beginning. If we would have used an array, we could have put all of those numbers in one single array, which is a 1000 times better than having to create a new variable for each number. It is a compliment in the world of programming if someone says your coding is dynamic. Arrays are in fact just that, dynamic.

Example
var example = new Array(“aa”,”bb”,”cc”);
example[3] = “dd”;
example[4] = “ee”;
document.write(example); // write out our entire array
document.write(“<br/>”); // line break
document.write(example[2]); // write out array item with an index of 2
Result
aa,bb,cc,dd,ee
cc

Common Array Properties

constructor – tells us the function that created the Array object’s prototype

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.constructor);
Result
function Array() { [native code] }

length – returns the total number of items in a array

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.length);
Result
3

Common Array Methods

As an object, arrays have a variety of methods. Since arrays are super dynamic, we have a lot of things we want to do with them. The creators of JavaScript gave us plenty of methods to use on our arrays.

concat() – this is the proper way to combine multiple arrays

Example
var example1 = new Array(“aa”,”bb”,”cc”);
var example2 = new Array(“dd”,”ee”,”ff”);
var example3 = new Array(“gg”,”hh”,”ii”);
var example4 = example1.concat(example2,example3);
document.write(example4);
Result
aa,bb,cc,dd,ee,ff,gg,hh,ii

indexOf() – finds item and returns it’s position

Example
var example = new Array(“aa”,”bb”,”cc”,”cc”);
document.write(example.indexOf(“cc”));
Result
2

lastIndexOf() – finds item’s finale occurrence and returns it’s position

Example
var example = new Array(“aa”,”bb”,”cc”,”cc”);
document.write(example.lastIndexOf(“cc”));
Result
3

join() – joins all of the elements in an array into a string (values separated by a comma)

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.join());
Result
aa,bb,cc

slice() – selects and returns part of an array

Example
var example = new Array(“aa”,”bb”,”cc”,”dd”);
document.write(example.slice(2,4)); 
Result
cc,dd

reverse() – reverses the order of the array

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.reverse());
Result
cc,bb,aa

sort() – sorts elements as you would expect

Example
var example = new Array(“dd”,”cc”,”bb”,”aa”);
document.write(example.sort()); 
Result
aa,bb,cc,dd

splice() – add and/or removes elements from array

Example
var example1 = new Array(“aa”,”bb”,”cc”,”dd”);
example1.splice(2,1);
document.write(example1);
document.write(“
“); // line break

var example2 = new Array(“aa”,”bb”,”cc”,”dd”);
example2.splice(1,1,”ee”,”ff”);
document.write(example2);
Result
aa,bb,dd
aa,ee,ff,cc,dd

push() – adds items to the end of array, and returns position of the added item

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.push(“dd”));
Result
4

pop() – removes and returns the last item of the array

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.pop()); 
document.write(“
“); // new line
document.write(example);
Result
cc
aa,bb

shift() – removes and returns the first item of the array

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.shift()); 
document.write(“
“); // new line
document.write(example);
Result
aa
bb,cc

unshift() – adds item to beginning of the array and returns its new length

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.unshift(“zz”)); 
document.write(“
“); // new line
document.write(example);
Result
4
zz,aa,bb,cc

XMLHttpRequest Object

For now, let’s discuss what an AJAX XMLHttpRequest Object is. It is an object that we use in AJAX that allows us to talk to a server behind the users back. This object is the sole reason we are allowed to make updates into the user’s page without forcing them to reload the entire page. An HTTP Request is actually sent out by your browser each time you type a website, which is then sent to a server that finally sends you back the web page. Of course, this happens right before your eyes and you know what it is doing. The XMLHttpRequest is very much like that, but it is very sneaky. The XML is simply a reference to the data structure that is being returned. Now, we can vent about Internet Explorer. Don’t get me wrong. I love Microsoft, but I absolutely hate the tyranny it has on developers. I will vent my anger more as we move through this tutorial.

Let’s make an XMLHttpRequest:

Example var xmlhttp;
if (window.XMLHttpRequest)
{ // works with IE7+, Chrome, Firefox, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // works with IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

It is the else statement that annoys me about Internet Explorer. However, you can see that they now have jumped on the bandwagon and started using XMLHttpRequest. Now, we can start sending requests to the server.

To GET Or To POST?

I won’t go into much detail here, but GET is usually the best because it is faster. However, you might want to use POST when you are transferring a very large amount of data. GET actually has a limit to the maximum allowed size for a url.

We will only deal with the GET

Example //PHP File <?php
echo $_GET[‘sampleVar’];
?>
//end PHP File
//HTML File
<script type="text/javascript">
function doGET()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() //This part is actually executed last
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) // Was the request processed successfully?
{
document.getElementById("sampleDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajaxTest2.php?sampleVar=" + Math.random());
xmlhttp.send();
}
</script>
<button type="button1" onclick="doGET()">GET</button>
<div id="sampleDiv">Nothing is here</div>

Obviously, call the function doGet() by clicking our button1. In that function, we have the standard setting up of our xmlhttp variable, creating the actual XMLHttpRequest. Next, we skip over the xmlhttp.onreadystatechange=function().

When then prepare to send our request with xmlhttp.open(“GET”,”ajaxTest2.php?sampleVar=” + Math.random(),true);. Let’s break this down a little bit. The “GET” is the request type. The ajaxTest2.php is the url that we are going to talk with. After the separating ?, we have a variable, sampleVar that is equal, =, to our Math.random(). The Math.random() simply generates a random number between 1 and 0. We use this so that our changed page won’t be cached by the browser. Finally, we send the request with xmlhttp.send();.

Eventually, the xmlhttp.onreadystatechange=function() will fire when the request returns with data. In that function, we set our sampleDiv‘s content equal to our returned data, xmlhttp.responseText, which in this case is whatever our Math.random() is. As you can see, every time you click the button the Math.random() variable is sent to the PHP file that spits out the variable’s value into the sampleDiv container.

Ajax Introduction

AJAX stands for Asynchronous JavaScript and XML. It is a complete game changer when it comes to user experience. Normally, web pages are loaded one at a time. When a user wants more content, they click a link. With AJAX, a user can click something and content can be loaded into the page, using JavaScript, without reloading the entire page.

Essentially, the user does some event that fires off an AJAX HttpRequest after an XMLHttpRequest object has been created. The server then processes the HttpRequest, and returns the data back to the browser. Now without JavaScript, it would be entirely worthless unless you were posting data to a database. We will set up our AJAX so it calls a JavaScript function, known as a Callback Function, to use our returned data from the server in the next tutorial.

Why Use jQuery Instead?

Learning AJAX is a great feat for any developer, but when it comes to developing, it is usually best to keep it simple. jQuery already has methods of JavaScript functions that do almost everything AJAX can do. What’s the point in rewriting long code that is already available to you? There isn’t. So, if you really love the fundamental understanding of programming read the AJAX tutorials. If not, read the AJAX tutorial under jQuery.

jQuery With HTML

We haven’t really changed any HTML elements just yet. Well now, we are here. jQuery simplifies about anything you want to do with HTML elements. jQuery’s primary purpose is to modify a web document’s HTML and CSS files, but how do we actually change HTML elements. We can insert new elements, remove elements, or even edit them using jQuery’s selectors that you read about earlier.

Generally when using jQuery with the intent to change the styling of an element, you want to do one of two things: add/remove a class to it or just change one CSS property. I would argue that it is a much better practice to always add or remove class, even if it is just one property, to/from an element. The reason being that classes are easily selected, but CSS properties require more work.

However, you can also use jQuery to modify the content of an element. You can append items before, after, or inside an element. I will show an example of modifying the entire content, but feel free to play around with these selectors and jQuery functions because they truly are a great asset to any web developer.

Example
<button id="button1">Click Me!</button>
<p id="someId">Something</p>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
    $("#button1").click(function()
    {
        $("#someId").html("Something Else");
    });
</script>

Common HTML Methods

  • addClass() – adds a class to the selected element
  • after() – adds content after the selected element
  • append() – adds content at the end selected element
  • attr() – adds an attribute to the selected element
  • before() – adds content at the before the selected element
  • html() – sets or gets the contents the selected element
  • remove() – removes the selected element
  • removeClass() – removes a class of the selected element
  • replaceWith() – replaces selected element with new content

Those are just a few common methods to edit HTML elements. Of course, you can always use jQuery’s references.

jQuery With CSS

jQuery makes working with CSS a breeze. The method here is .css(), and it is used very much like the other methods or actions in jQuery. While this entire tutorial will go against my conventional logic of only appending or removing classes, many of you will do it this way because it is much more simple. I must admit that it is a very quick and efficient way of applying CSS properties to an HTML element. Please just don’t paint yourself in a corner using the css method after a selector more than a few times on a single element.

The jQuery CSS Method has three different structures for its 3 different arguments.

  • .css(name) – returns the CSS property of the value
  • .css(name,value) – sets a CSS property
  • .css({properties}) – sets multiple CSS properties

We will use the first two in this example.

Example
<div id='firstDiv' style="width:150px; background-color:#D2BA0D;color:#000000;">firstDiv</div>
<div id='secondDiv' style="width:30px; background-color:#238B0A;color:#000000;">SecondDiv</div>
<input id='buttonOneId' name="buttonOne" type="button" value="Do Something!"/>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
    $("#buttonOneId").click(function()
    {
        var firstWidth = $('#firstDiv').css('width');
        $("#secondDiv").css("width",firstWidth);
    });
</script>

It is really just that simple. If you have ever had 2 or 3 divs inside 1 containing div, you know how hard it is to make all of the columns the same height or width. With JQuery, it is really just that simple. Of course, if you won’t usually use a button to change CSS in that way, but you still may find yourself using events to change CSS for some other good reason. It would get very tedious if you wanted to change large amount of CSS properties, which is why we have the third syntax of the css() method.

Example
<div id='thirdDiv' style="width:150px; height:40px; background-color:#FDE80B;color:#000000;">firstDiv</div>
<div id='fourthDiv' style="width:30px; background-color:#238B0A;color:#000000;">SecondDiv</div>
<input id='buttonTwoId' name="buttonTwo" type="button" value="Do Something!"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
    $("#buttonTwoId").click(function()
    {
        var thirdWidth = $('#thirdDiv').css('width');
        var thirdHeight = $('#thirdDiv').css('height');
        var thirdBG = $('#thirdDiv').css('background-color');
        $("#fourthDiv").css({"width":thirdWidth,"height":thirdHeight,"background-color":thirdBG});
    });
</script>