How to Use the jQuery replaceWith Method

When you need to completely remove on element and put another in its place

One of the fun things about jQuery is learning about a method that introduces you to a DOM manipulation scenario you may not otherwise have thought of. The replaceWith() method allows you chop out one piece of the page and replace it with anther. The details of either are not important. You simply specify the original section of the DOM as well as the new chunk, and poof! done.

Example # 1

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>jQuery replaceWith() Example</title>
       <script language="javascript"  src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    </head>
	<script id="demo" type="text/javascript">
		$(document).ready(function() {
			$("#foo").click(function(){
				$(this).replaceWith("<ul><li>one</li><li>two</li><li>three</li></ul>");
			});
		});
	</script>
    <body>
		<div id="foo">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla at lectus erat.</div>
    </body>
</html>

In example # 1, we have attached an event handler to the element with the id: “foo”. When clicked, that element is removed from the page, and replaced with a piece of markup defined in a string. Yes, it’s that easy, and there are certainly more interesting things you can do with this jQuery method.

Summary

Replacing one section of the page with another piece of markup is quite each with the jQuery replaceWith() method. The syntax is very strait-forward and if you are already familiar with jQuery, there are quite a few possibilities.

Helpful links for the jQuery replaceWith method

http://api.jquery.com/replaceWith/

http://www.w3schools.com/jquery/html_replacewith.asp

http://stackoverflow.com/questions/730916/whats-the-difference-between-jquerys-replacewith-and-html

http://stackoverflow.com/questions/5248721/jquery-replacewith-fade-animate

JavaScript Interview Questions: Arrays


Q 1: Name two ways to dynamically add the value “bar” to the array “foo”

A:

foo.push("bar")

foo[foo.length] = "bar";

Hint: There are Two Ways to Dynamically Add an Element to a JavaScript Array


Q 2: Of what JavaScript type is an Array?

A: object

Hint: JavaScript arrays are Objects


Q 3: What property tells you the length of a JavaScript array?

A: The “length” property

More Info on the JavaScript Array’s “length” property:

http://www.roseindia.net/java/javascript-array/javascript-array-length-function.shtml

http://www.bloggingdeveloper.com/post/JavaScript-Array-Length-Property.aspx


Q 4: If the array “foo” has a length of 10, what is the index of the first element in the array?

A: 0

Hint: JavaScript Arrays are zero-based


Q 5: If the array “foo” has a length of 10, what is the index of the last element in the array?

A: 9

Hint: JavaScript Arrays are zero-based


Q 6: What is the syntax you would use to assign the first element in the array “foo” to the variable “bar”?

A:

var bar = foo[0];

Q 7: True of False: An element in a JavaScript array an be another array

A: True

Hint: JavaScript Array elements can be arrays


Q 8: Given the following line of code, what is the length of the array “foo”?

var foo = [];

A: 0

Hint: foo is an Array literal, but in this line of code, no elements have been defined.


Q 9: What does the array.shift() method do, and what does it return?

A: It removes the first element from the array and returns that element

More info on the JavaScript array.shift() method:

http://www.w3schools.com/jsref/jsref_shift.asp

http://www.bennadel.com/blog/1796-Javascript-Array-Methods-Unshift-Shift-Push-And-Pop-.htm

http://www.devguru.com/technologies/ecmascript/quickref/shift.html

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/shift


Q 10: Given the following line of code, what would be the output of the console?

var foo = new Array(3);
console.log(foo);

A:  [undefined, undefined, undefined]

Hint: When you instantiate the JavaScript Array() constructor, and pass in a single number, that number will indicate the length of the array, but the elements are still not initialized (i.e. they are all undefined)


Helpful Links for JavaScript Arrays

W3C Schools

http://www.w3schools.com/js/js_obj_array.asp

Mozilla Developer Network

https://developer.mozilla.org/en-US/search?q=javascript+array

JavaScriptKit

http://www.javascriptkit.com/jsref/arrays.shtm

JavaScript Mountain

http://javascriptmountain.com/?s=array

The JavaScript for…in statement – enumerating object properties

JavaScriptThe JavaScript “for in” statement allows you to literally “loop” through all the properties of an object, without knowing ahead of time what the object will be or how many properties it will have

One of the most over-looked and under-used tools in the JavaScript language is the “for in” statement. This statement allows you to essentially say: “Hey, if I have an object, any object, I wanna know what the name and value of every one of it’s properties is”

No problem dude.

The “for in” statement creates a loop, much like the typical “for ( i=0, i <+ ###, i++)”, but  you can think of it as more of: “for (x = the first property in an object, go until x == the last property in the object, go to the next property in the object”). Needing to know all the names and values of a given object at run time is a scenario that comes up more than you may think, and being able to satisfy that need is a huge (huge) asset.

Example # 1

var car = {
   maker: "honda",
   color: "blue",
   type: "sedan",
   mpg: "32"
}

for (var prop in car){
console.log( "The " + prop + " of this car is: " + car[prop] );
}

In example # 1, we created a JavaScript object literal and assigned it to the variable “car”. This object has four properties. We then use a JavaScript “for in” loop to literally loop through the properties of this object. note that in order to build our dynamic statement, we first reference “prop”, which is the variable that represents the name of the currently examined property (i.e. “maker”). In order to the actual value of prop, we use bracket syntax, as opposed to dot notation or dot syntax. This is because in order to use dot notation, we would have to actually know the name of the property (i.e. “car.maker”). Since we only have a variable to use, we can say “car[prop]“, because bracket notation allows us to use a variable, or any valid JavaScript expression inside the bracket.

The output of example # 1 would be:

The maker of this car is: honda
The color of this car is: blue
The type of this car is: sedan
The mpg of this car is: 32

Summary

The JavaScript for..in statement is easy to use and incredibly useful. It helps to write code that deals with objects that are unknown at run time, but as a result, can be easily enumerated and acted upon.

Helpful links for the JavaScript “for in” statement

http://www.w3schools.com/js/js_loop_for_in.asp

http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/

http://webreflection.blogspot.com/2009/10/javascript-for-in-madness.html

How to use the JavaScript indexOf() method to find the position of one string in another string

The JavaScript indexOf() method allows you to find out if a string contains one or more characters, and if so, the starting position of that set of characters

If you’ve ever found yourself saying: “How do I figure out of one string contains a certain character or a sub-string?” then the JavaScript indexOf() method is for you. It returns the starting position of a string, even it is one character. If that string does not exist, then it returns “-1″. So, if you want to know if a given string even exists at all in another string, simply test to see if the JavaScript method indexOf() returns “-1″or not. If it does, then the sub-string does not exist. If the return value is “> -1″ (i.e. more than -1), then the string does exist.

Example # 1

var foo = "Hello world";
var bar = foo.indexOf("football")
console.log(bar);

In example # 1, we check for the starting position of “football” within the string “Hello world”. Because “football” does not exist in “Hello world”, the return value is “-1″

Example # 2

var foo = "Hello world";
var bar = foo.indexOf("football")

if ( bar === -1 ){
    console.log('"football" does not exist in the string "hello world"');
} else {
    console.log('"football does exist in the string "hello world"');
}

In example # 2, we use an “if else” condition to test for the string “football” in “hello world”, in this case, it does not exist.

Example # 3

var foo = "Hello football world";
var bar = foo.indexOf("football")

if ( bar === -1 ){
    console.log('"football" does not exist in the string "hello world"');
} else {
    console.log('"football does exist in the string "hello world",
    and the starting position of that string is: ' + bar);
}

In example # 3, we have included the string “football” in “hello world”, so the test returns the starting value of ”football”, which is “6″. So, the test evaluates to “true”, the “true” text is displayed, and at the end of that text, we return the starting position of ”football”.

Summary

The JavaScript indexOf() method is the best way to find out if one string exists inside of another. If it does, the starting position of that searched string is returned. If the sub-string does not exist, then “-1″ is returned, which is  a reliable indicator of “does not exist”.

Helpful links for the JavaScript indexOf() method

http://www.w3schools.com/jsref/jsref_indexof.asp

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

http://www.tizag.com/javascriptT/javascript-string-indexOf.php

 

JavaScript Interview Questions: Object-Oriented JavaScript

Q 1: True or False: When you create an object literal, you must first instantiate the Object constructor

A: False

Explanation:

In order to create an Object Literal, you assign a variable to an object. The syntax is as simple as var foo = {}. A constructor function is used when creating an instance object, which is a different process.


Q 2: True or False: Once you create an object, you can add, remove or change properties of that object at any time.

A: True

Explanation: JavaScript object are mutable.


Q 3: True of False: A JavaScript array is not an object

A: False

Explanation: JavaScript arrays are objects. They inherit from the JavaScript Object, and have methods and properties that are specific to arrays such as “length” and “sort


Q 4: What is the difference between using dot notation and bracket notation when accessing an object’s property?

A: If using the not notation, the property must be a string and refer to a property that exists. When using bracket notation, any valid JavaScript expression that produces a value can be used inside the brackets, such as a variable or an an array element.

Hint:

These are all valid lines of code:

foo bar.name;
foo = bar["name"];
foo = bar[5 + 5];
foo = bar[ baz() ];
foo =bar[ baz[i] ];

Q 5: What is important to remember about the last property’s value in a JavaScript object literal?

A : The last property’s value should not be followed by a comma.

Hint: Most browsers will let you get away with it if you forget, but Microsoft Internet Explorer will complain about the extra comma.


Q 6: Given the following code, what is very likely the reason that the programmer made the first letter of “Foo” a capital letter?

var Foo = function(){
this.foo = "bar";
}

A: Foo is meant to be used as a constructor function


Q 7: Given the following code, how would you instantiate the function “Foo” and assign it to the variable “bar”?

var Foo = function(){}

A:

var bar = new Foo();

Q 8: What is the difference between a constructor function and a non-constructor function with regards to the word “this”

A: In a non-constructor function, “this” refers to the global context or if the function is executed inside of another function, it refers to the context of the outer function. In the instance object that is returned by a constructor function, “this” refers to the context of that function.

Explanation: JavaScript constructors are more useful when you understand how they behave differently from normal JavaScript functions and Object Literals.


Q 9: True of False: You can only instantiate a JavaScript constructor function once.

A: False

Explanation: You can make as many instances as you want.


Q 10: How do you determine if a JavaScript instance object was created from a specific constructor or not?

A: Use the instanceof operator

Helpful links for the JavaScript instanceof operator:

https://developer.mozilla.org/en/JavaScript/Reference/Operators/instanceof

http://stackoverflow.com/questions/2449254/what-is-the-instanceof-operator-in-javascript

http://skilldrick.co.uk/2011/09/understanding-typeof-instanceof-and-constructor-in-javascript/

http://javascript.gakaa.com/operators-instanceof.aspx


Two Alternatives to the jQuery Document Ready Function for JavaScript

jQuery LogoThere are two alternatives to document ready that are a bit easier to type

Most JavaScript programmers are familiar with jQuery’s document ready function. There is no doubt that it is a very helpful way to wrap your JavaScript with a cross-browser compatible function that will not run until the document has achieved a “ready” state. While the syntax is fairly simple, there are two slightly less verbose alternatives to the exact same functionality.

Example # 1

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Three variations on the jQuery document ready function</title>
        <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
        <script>
        $(document).ready(function(){
          console.log("the document is ready")
        });
        </script>
    </head>
    <body>
    </body>
</html>

In example # 1, we have the standard syntax for the jQuery document ready function.

Example # 2

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Three variations on the jQuery document ready function</title>
        <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
        <script>
        $(function(){
          console.log("the document is ready")
        });
        </script>
    </head>
    <body>
    </body>
</html>

In example # 2, we omit the “document / ready” portion of the equation, and simply insert our function in the following expression $().

Example # 3

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Three variations on the jQuery document ready function</title>
        <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
        <script>
        $().ready(function(){
          console.log("the document is ready")
        });
        </script>
    </head>
    <body>
    </body>
</html>

In example # 3, we chain a the jQuery ready() function to the return value of the jQuery object: $().ready(). So, when the jQuery object is ready, so is our code.

Summary

There is no doubt that the jQuery document .ready() function is super-useful. There is however, more than one way to invoke this functionality.

Helpful links for the jQuery document .ready() function

http://api.jquery.com/ready/

http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

http://rpheath.com/posts/403-jquery-shorthand-for-document-ready

http://think2loud.com/653-jquery-document-ready-howto/

 

 

 

Why is a JavaScript array’s length property always one higher than the value of the last element’s index?

JavaScriptThe “length” property of a JavaScript array is a very helpful tool, but why is it always one “off”?

Array in JavaScript are zero-based. This means that JavaScript starts counting from zero when it indexes an array. This means that the index value of the first element in the array is “0″ and the index value of the second element is “1″, the third element’s index value is “2″, and so on. This is not unusual in computer programming languages.

The JavaScript array length property is given in a one-based context. So, a JavaScript array with one element will have a “length” of “1″. If a JavaScript array has four element, then that array’s “length” property will have a value of “four”. But (and here is the point where many get confused), if a JavaScript array has four elements, the last element has an index of “3″. This is because again, JavaScript arrays are zero-based.

Example # 1

var arr = ["monday","tuesday","wednesday","thursday","friday"];

console.log(arr.length);

In example # 1, we have an array with five elements. The console.log() statement reflects this as well because the “length” property of this array is “5″ (i.e. this is a one-based value).

Example # 2

var arr = ["monday","tuesday","wednesday","thursday","friday"];

var len = arr.length - 1;

for (var i = 0; i <= len; i++){
console.log( "The value of element # " + i + " is: " + arr[i] );
}

In example # 2, we create a variable who’s value is one LESS than the length of our array. So, since our array’s “length” property is “5″, our “len” variable is equal to “4″. Our loop will start at 0, and run util i equals “4″. This IS five iterations, but we are starting at 0, not one. So, since JavaScript starts counting Arrays from Zero, our code successfully outputs the value of each element in the array.

Summary

JavaScript arrays are zero-based. The JavaScript array “length” property returns the number of elements in an array, but it is a one-based value. So whenever you want to use the “length” property to say “hey, start from the first element in an array and go until you reach the last element, start from zero, and go until you reach the array’s “length” property value, but “minus one!”

Helpful links for the JavaScript array’s length property

http://www.w3schools.com/jsref/jsref_length_array.asp

http://www.w3schools.com/jsref/jsref_obj_array.asp 

http://www.plus2net.com/javascript_tutorial/array-length.php

http://www.plus2net.com/javascript_tutorial/array-length.php 

What is the difference between an Object Literal and an Instance Object in JavaScript ?

Although a JavaScript object literal and a JavaScript instance object are both objects, they differ in their inherent nature and features


Object Literals

An object literal is “flat”. You create it, you add properties and methods to it, and all of those properties and methods are public. You can mutate any members of that object at any time. A JavaScript object literal does not provide any kind of private scope or private variables. Although, any of the members of an object literal an certainly be a function that provides these features. Object literals are useful because they are a lightweight way of providing multidimensional data in a way that is easy to pass around and consume.

Example # 1

var data = {
    fname: "foo",
    addOne: function(num){ return num + 1}
}

console.log(data.fname)
console.log(data.addOne(4))

data.fname = "bar";
console.log(data.fname)

data.lname = "baz";
console.log(data.lname)

data.say = function(){ return "this is the say function" };
console.log( data.say() );

In example # 1, we have defined a JavaScript object literal and assigned it to the variable “data”. This object has two members; the property “fname” and the method “addOne”. At run time, we can mutate this object very easily and add new properties (i.e. “lame”) and methods (i.e. “say”). The upside is that this object is totally exposed and we can access or mutate any of its members any time we like with no problem (remember though that if an object member is a function, then that function does provide its own private scope and that scope is not accessible to us). The downside of this object is that it does not inherently have a private scope, nor is there the kind of initialization that is provided by a constructor upon creation.

The output for example # 1 is:

foo
5
bar
baz
this is the say function

Instance Objects

An instance object is what is returned when instantiating a JavaScript constructor function, using JavaScript “new” keyword. When you say “var a – new b()”, “a” becomes an “instance” of the fuction “b()”. Any expressions within b() are executed, any local variables in b() are copied and provided in “a”, and the value of “this” inside of “a”, refers to the context inside of “a”. The function “b” is never touched or changed, it simply acts as a “blueprint” for “a”, and “a” is an “instance” of “b”. Any local variables inside of “a” are not accessible outside of “a” and can only be muted by privileged members of “a”.

Example # 2

var Foo = function(){
	var _color= "blue";
	console.log("welcome to your new instance object");
	this.getColor = function(){
		return _color;
	}
	this.setColor = function(newColor){
	   _color = newColor;
	}
}

var bar = new Foo(); // "welcome to your new instance object"
console.log(bar._color); // undefined
console.log(bar.getColor()); // "blue"
bar.setColor("red")
console.log(bar.getColor()); // "red"

In example # 2, we have created a constructor function. A JavaScript constructor function is a function that is not meant to be executed directly, for example we never plan to do the following: “Foo()”. Instead, a constructor is meant to be instantiated. This means that you create an “instance” of that function using the JavaScript “new” keyword. We have created an instance of Foo() by saying “var bar = new Foo()”. We now have a variable named “bar” that is an exact copy of Foo().

What makes “bar” differ from our JavaScript Object Literal that we defined in example # 1, is that when our instance object (“bar”) is created, any execution code in the constructor (i.e. “Foo()” ) runs, and any private variables defined in the constructor remain private in the instance object (i.e. “_color”).

What makes this scenario a little more special than that of the object literal is that we can have privileged methods. These are methods that are made public by the use of the “this” prefix, but they have access to the instance object’s private members (i.e. “_color”). So, when we run this code, the constructor function code runs (“welcome to your new instance object”), we attempt to output the value of “_color”, but “undefined” is returned, becase “_color” is private and cannot be accessed outside of “bar”. We then use the privileged method “getColor()” to get the value of _color the correct way, and “blue” is returned. We then change the value of “_color” using the privileged memer “setColor()”, and return it’s value using “getColor()” again (“red”).

Summary

Both Object Literals and Instance Objects have their place and purpose in JavaScript. The power of Object Literals is in their lightweight syntax and ease of use. The power of instance objects is that they provide private scope and initialization code that runs when they are created.

Helpful links for JavaScript Objects

http://www.w3schools.com/js/js_objects.asp

http://www.javascriptkit.com/javatutors/oopjs.shtml

http://www.dyn-web.com/tutorials/obj_lit.php

http://www.davidpirek.com/blog.aspx?n=JavaScript-Class-Constructor-vs.-Object-Literal:-Difference-in-Implementation-and-Inheritance

Using an Immediate Function to Create a Global JavaScript Variable That Has Private Scope

JavaScriptKeeping the global name space clean is a good idea. Immediate functions allow the JavaScript programmer to do so with a great deal of power

In a previous post, we discussed the topic of the JavaScript Immediate Function. Let’s re-visit this topic with a focus on creating a private scope that we can interact with.

Most JavaScript programmers know that you can create an object, and then extend that object by simply assigning a new property to that object. You can even do so at run time. This is all very nice, but as you do so, these new properties are public. They are accessible to anyone and mutable at any time. While this can have it’s uses, there is a downside in that any line of code has access to these properties and can change them. Sometimes, that can get messy.

Example # 1

var foo = {};
foo.name = "bart";
foo.say = function(){};

In example # 1, we created a global variable named “foo”. We then added two properties to it: “name” and “say”. There is no reason why at a later point in our code, we couldn’t intentionally ( or even worse, accidentally) do the following:  foo.name = “marge”. If this is intentional, no problem, but if it is done by accident, it creates cases that become frustrating to debug and manage. What we need is a way to store values inside of foo that have a clearly defined interface for retrieval and mutation.

Example # 2

var foo = (function(){
    var _name = "bart";
    var MyConstructor = function(){
        this.getName = function(){
            return _name;
        };
        this.setName = function(newName){
            _name = newName;
        };
    }
    return new MyConstructor();
})();

console.log( foo.getName() );
console.log( foo.setName( "simpson" ) );
console.log( foo.getName() );

In example # 2, we have drastically altered our global variable so that it is an immediate function. Inside of that immediate function, we have a private variable called “_name”. We return an instance of our constructor function, which allows us to use the “this” keyword to create privileged members. These two functions allow us to set, and get the value of name. If you paste example # 2 in your JavaScript console, and run it, you will sett that the value of our private variable “_name” changes over the course of the two “get” statements. This is because in-between these two get statements, we use the “setName” method to change the value of that private variable.

Summary

The JavaScript immediate function can be used to create a global variable that has it’s own private scope. This useful when creating functionality that requires storing data for the life of the page and managing access to that data.

Helpful links for SUBJECT

http://javascriptmountain.com/tag/immediate-function/

http://dreaminginjavascript.wordpress.com/2008/07/03/immediate-execution/

http://lostechies.com/derickbailey/2011/12/04/achieving-block-scope-with-immediate-functions-in-javascript/

http://www.jameswiseman.com/blog/2011/02/17/jslint-messages-wrap-an-immediate-function-invocation-in-parentheses/

http://www.jspatterns.com/self-executing-functions/

 

 

Understanding the Difference between null and undefined in JavaScript

JavaScript

It is quite common to confuse these two, but there is an important difference between them

Things can get murky quickly when using null or undefined in test cases if you are not clear about the difference between them.

null

Simply put: null is a JavaScript keyword that indicates the absence of a value. Surprisingly, if you run the following in your firebug console:  console.log( typeof null ), you will see “object”. Don’t be fooled though. This object is not mutable, has no properties, and there is at all times, only once instance of it. It simply evaluates to “no value”. Although, this is a perfectly valid value in JavaScript. If you want to strip a variable of any value, assign it to “null”.

Example # 1

var foo = {};
console.log("foo is a type: " + typeof foo); //foo is a type: object
var foo = null;
console.log("foo is a type: " + typeof foo); //foo is a type: object
console.log("the value of foo is: " + foo); //the value of foo is: null

In example # 1,  we created an object called “foo”. The console.log statements demonstrate the odd, yet perfectly valid behavior of “null”. At first the type of foo is “object”, After we assign foo to null, it is still an “object” type, yet when we console.log the value of foo, it is simply “null”

undefined

In JavaScript, “undefined” is a global variable (a property of the global object), that is created at run time. This global variable represents something  that has not been initialized, as well as an object property or array index that does not exist. Also, when you do not supply an argument for a function parameter, it will have the value of “undefined”. Furthermore, when a function does not return a value, it returns “undefined”. Have you ever wondered why sometimes when you execute a function in the FireBug console, you see “undefined” in the console? That is because while your function may actually do something wonderful, if it does not explicitly return a value, then it returns “undefined”.

Example # 2

console.log("foo is a type: " + typeof foo); //foo is a type: undefined
console.log("the value of foo is: " + foo); // ReferenceError: foo is not defined

In example # 2, when we attempt to determine what type “undefined” is, we are told that it is of the type “undefined”.  Hence, there is only one instance of the “undefined” value, and it has the value of “undefined” (do you have a headache yet?). In the second line, we attempt to output the value of foo to the console, but we get a “ReferenceError”. This is because while asking what the type of an undeclared variable is does not harm anyone (it is the type “undefined”), attempting to access that variable causes an error because it essentially does not exist. But, if we assigned foo to “null”, and then tried to access it, no problem. This is because if we assign foo to “null”, it has a value, and that value is “null” (i.e. “no value”), but when something evaluates to “undefined”, it does not exist.

Summary

In JavaScript, “null” and “undefined” have different meanings. “null” is a special keyword that indicates an absence of value, while “undefined” means: “it does not exist”.

Helpful links for JavaScript “null” and “undefined”

http://saladwithsteve.com/2008/02/javascript-undefined-vs-null.html

http://weblogs.asp.net/bleroy/archive/2005/02/15/Three-common-mistakes-in-JavaScript-_2F00_-EcmaScript.aspx

http://sharkysoft.com/tutorials/jsa/content/045.html

 

Older posts «