Build Inbound Links with Online Promotion

Now that your website is keyword-optimized, it is time to build up your inbound
links. Promoting your site to build more inbound links than your competitors, especially
from high PageRank sites, is the most important way to increase your search
engine rankings. Here are some techniques you can use to boost your inbound links
to build up the buzz and rise above the noise:
• Use XML news feeds such as RSS and Atom to automatically syndicate your content
to other sites.
• Register your feeds at news aggregators.
• Interview luminaries.
• Write articles on your most important topics for other sites, and have your bio
link back to your website.
• Create useful tools.
• Publicize new content with press releases.
• Get listed in the major directories in the appropriate category:
— http://dir.yahoo.com
— http://www.business.com
— http://www.dmoz.org
— http://botw.org
• Get listed in industry directories and resource pages (e.g., the WorkForce.com
Vendor Directory for HR software providers at http://www.workforce.com/global/
2007/vendormain07.htm).
• Get links from industry websites and discussion forums (write articles, send
press releases, post to forums, and use your link in signature files).
• Use “high-end”link

Web page optimization streamlines

Your pages to download and display faster. As
your website performance improves, your bailout rates and bandwidth bills will go
down while your conversion rates and profits will rise. In this chapter, you learned
how to minimize HTTP requests, optimize graphics and multimedia, substitute
server-side for client-side sniffing, and load JavaScript wisely.

To reduce the overhead of multiple objects that causes the majority of web page
delay, minimize the number of objects referenced within your web pages. Also, put
all of your images, still and motion, on a strict file size diet. Minimize the size of the
head of your HTML, and layer your markup to display useful content quickly and
maximize your potential search engine rankings. Finally, move your CSS to the top
and your scripts to the bottom of your pages to enable progressive display.

Top Search Engine Ranking Factors

PageRank is not the only factor that Google uses to rank search results. Google uses
more than 200 “signals”to calculate the rank of a page.a According to a survey of SEO
experts, the top 10 most important factors include the following:
• Keyword use in title tag
• Anchor text of inbound link
• Global link popularity of site
• Age of site
• Link popularity within the site’s internal link structure
• Topical relevance of inbound links to site
• Link popularity of site in topical community
• Keyword use in body text
• Global link popularity of linking site
• Topical relationship of linking page
The top factors that negatively affect a search engine spider’s ability to crawl a page or
harm its rankings are as follows:
• Server often inaccessible to bots
• Content very similar to or duplicate of existing content in the index
• External links to low-quality/spam sites
• Duplicate title/meta tags on many pages
• Overuse of targeted keywords (indicative of stuffing/spamming)
• Participation in link schemes or actively selling links
• Very slow server response times
• Inbound links from spam sites
• Low levels of visitors to the site

SEO Testing

SEO is both an art and a science. As with any scientific discipline, it requires rigorous testing
of hypotheses. The results need to be reproducible, and you have to take an experimental
approach so as not to modify too many variables at once. Otherwise, you will not be able to
tell which changes were responsible for the results.

And although you can glean a tremendous amount of knowledge of SEO best practices, latest
trends, and tactics from SEO blogs, forums, and e-books, it is hard to separate the wheat from
the chaff and to know with any degree of certainty that an SEO-related claim will hold true.
That’s where the testing of your SEO comes in: proving what works and what doesn’t.
Unlike multivariate testing for optimizing conversion rates, where many experiments can be
run in parallel, SEO testing requires a serial approach. Everything must filter through the
search engines before the impact can be gauged.

AdWords Tips For SEO

Observe and track your competition
Observe the competition. Write a script to track ads of your targeted keyword list.
Record competitor ads for several weeks. Note changes in ads. Analyze ads that
changed. If the ads are not changing, this could mean they are working.

Experiment
Don’t stop with weeding out the nonworking keywords. Experiment with new keywords.
Learn of any new competitors. Learn what their keywords are. Don’t be afraid
to gradually lower your bid prices to see the effects on your CTR.

Refine your ad copy
A poor CTR usually means bad ad copy, bad keyword targeting, and bad timing. You
can easily create several versions of your ads for your campaign. Use that to your advantage.
Learn which ads are converting and which are not. Learn which words are
being used in the ads that work and in the ads that do not. In general, the higher your
CTR, the lower your average cost-per-click will be.

Try other platforms
If you have stiff competition on AdWords, you may want to examine other PPC platforms.
Yes, search volumes may be lower, but less competition and more keywords of
interest could compensate for the lack of volume.
If you score a successful campaign with ads producing clicks and, ultimately, profits,
you may want to consider replicating the campaign across the other platforms—
especially Yahoo! and Microsoft. Replicating your winning formula is smart marketing.

SEO Benefits Of A Quality Website Structure

The main benefits of having a great navigation structure for both search engines and people
are:

Indexation - If the search engines such as Google can follow your structure from Homepage
right down to the lowest levels, then it will get to “crawl” (see) every page on the site. It means
that as long as the rest of the site is optimized correctly, every page on the site should be
indexed in the search engines.
Following on from this, any new pages you add should get indexed more quickly as the site can
be crawled more easily.
Usability - It gives a better impression of the website to the search engine due to its usability
for humans. Big search engines look for this mainly.
You should always focus at designing a simple website structure, as you should be going to
innumerable unknown users.
Page

SEO Research and Analysis

even more challenging and complex by the constant evolution of best practices and
optimization opportunities.
Fortunately, a great variety of resources that make the job easier are available on the Web.
Many leading SEO practitioners regularly post their thoughts on blogs or in forums, or speak
at conferences. This creates many opportunities to interact with them, learn from their
experience, and keep your skills sharp and up-to-date.
In this chapter, we will talk about those resources and how to leverage them to be more
successful in your SEO efforts.

SEO is rapidly evolving. Search engines are constantly changing their algorithms, and new
media and technologies are being introduced to the Web on a regular basis. Staying current
requires an ongoing commitment to research.


One of the easiest ways to research what is happening in the world of SEO is to study the
websites and periodicals that cover SEO in detail, but ongoing testing of SEO hypotheses should
also play a role.

SEO for Lead Generation and Direct Marketing

Although lead generation via the Web is less direct than an e-commerce transaction, it is
arguably just as valuable and important for building customers, revenue, and long-term value.
Millions of search queries have commercial intents that can’t be (or currently aren’t) fulfilled
directly online. These can include searches for services such as legal consulting, contract
construction, commercial loan requests, alternative energy providers, or virtually any service
or product people source via the Web.
Here are some factors to think about when considering SEO for lead generation and direct
marketing:

When to employ
Use it when you have a non-e-commerce product/service/goal that you want users to
accomplish on your site or for which you are hoping to attract inquiries/direct contact
over the Web.

Keyword targeting
As with e-commerce, choose phrases that convert well, have reasonable traffic, and have
previously performed in PPC campaigns.

Page and content creation/optimization
Although you might think it would be easier to rank high in the SERPs for lead generation
programs than for e-commerce, it is often equally challenging. You’ll need a solid
combination of on-site optimization and external link building to many different pages on
the site (with good anchor text) to be competitive in the more challenging arenas.

Search Ranking Algorithm-Social sharing data

Include social sharing and follow buttons on your site, your blog, and in
your emails

social sharing strategies increase traffic and increase profits. For
those internet marketers wondering how big can social media be in terms

of helping businesses online explode

 Twitter Followers -> Email Subscribers: Twitter is a great communication

channel. It helps you contact and stay in touch with anyone you want. But

it doesn’t directly make you real money. Email marketing is still the

most profitable online marketing channel.


Facebook Fans -> People Talking About This: Facebook’s EdgeRank was

designed to keep companies from spamming their “fans”. So it only allows

you to reach the fans that actively engage with your brand. “People

Talking About This” is the closest metric you have to increase your

“viral reach”. The higher that number goes, the better chance you have of

reaching more people. And the bigger your page will grow because you’ll

start reaching more “friends of fans”.

Techniques To Improve Page Rank

You can follow up certain methods for improving your page rank. One of the very common
methods followed often for this purpose is to increase the numbers of pages of the website and
interlinking them with each other. However, you need to take care so that your website is
significant and it contains meaningful content for use. Otherwise, your website may obtain a
negative ranking in the search engines if your website has empty pages without any particular
substance.

Link building is another method for improving page ranking. The incoming backlinks play
significant role in this direction. It is again a mathematical formula for improving page rank. A
high ranked page link certainly improves your page ranking. Some other advertising strategies
can also help you out in this direction.

Page ranking has utmost importance for your website. A high page ranked website always
attains higher page rank backlinks. However, this depends on other traits of your website like
quality content and other services.

SEO for Raw Traffic

Optimizing a site for search engines and creating keyword-targeted content helps a site rank
for key search terms, which typically leads to direct traffic and referring links as more and more
people find, use, and enjoy what you’ve produced. Thousands of sites on the Web leverage
this traffic to serve advertising, directly monetizing the traffic sent from the engines. From
banner ads to contextual services such as Google’s AdSense program to affiliate programs and
beyond, web advertising has become a massive industry—$25 billion plus, according to
eMarketer.

Here are some factors to think about when considering SEO for raw traffic:
When to employ
Use it when you can monetize traffic without actions or financial transactions on your site
(usually through advertising).
Keyword targeting
Keyword targeting in this scenario can be very broad. The goal here isn’t typically to select
specific keywords, but rather to create lots of high-quality content that naturally targets
interesting/searched-for terms. Instead of singular optimization on specific terms, the
focus is on accessibility and best practices throughout the site to earn traffic through both
high volume and long tail queries (for more on what long tail is, see Chapter 5).
Concentrate efforts on great content, and use keyword-based optimization only as a
secondary method to confirm the titles/headlines of the works you create.
Page and content creation/optimization
A shallow, highly crawlable link structure is critical to getting all of your content indexed—
follow good information architecture practices.You’ll also need to
employ good on-page optimization (titles, headlines, internal linking, etc.) and make your
articles easy to share and optimized for viral spreading.

SEO for Reputation Management

SEO for reputation management is a process for neutralizing negative mentions of your name
in the SERPs. In this type of SEO project, you would strive to occupy additional spots in the
top 10 results to push the critical listing lower and hopefully off the first page. You may
accomplish this using social media, major media, bloggers, your own sites and subdomains,
and various other tactics.


Since one’s own name—whether personal or corporate—is one’s identity, establishing and
maintaining the reputation associated with that identity is generally of great interest.
Imagine that you search for your brand name in a search engine and high up in the search
results is a web page that is highly critical of your organization.

SEO for E-Commerce Sales

One of the most direct monetization strategies for SEO is driving relevant traffic to an ecommerce
shop to boost sales. Search traffic is among the best quality available on the Web,
primarily because a search user has expressed a specific goal through her query, and when this
matches a product or brand the web store carries, conversion rates are often extremely high.

When to employ
Use it when you have products/services that are directly for sale on your website.
Keyword targeting
Paid search advertising is an excellent way to test the efficacy and potential ROI of keyword
targets. Find those that have reasonable traffic and convert well, and then pursue them
further. You’ll often find that the more specific the query—brand-inclusive, productinclusive,
and so on—the more likely the visitors are to make the purchase.
Page and content creation/optimization
You’ll typically need some serious link building, along with internal optimization, to
achieve high rankings for competitive, high-value keywords that bring in conversionfocused
traffic. Manual link building is an option here, but scalable strategies that leverage
a community or customers can be equally, or even more, valuable.

Javascript Math object

The Math object holds a set of constants and methods enabling more complex mathematical operations than the basic arithmetic operators

var root = Math.sqrt(10);


Constants Provided by the Math Object
Property
Description
Math.E
The base of the natural logarithm (Euler's constant e)
Math.LN2
Natural log of 2
Math.LN10
Natural log of 10
Math.LOG2E
Log (base 2) of e
Math.LOG10E
Log (base 10) of e
Math.PI
Pi (p)
Math.SQRT1_2
Square root of 0.5 (equivalently, one over the square root of 2)
Math.SQRT2
Square root of 2
Table 7-4: Methods Provided by the Math Object
Method
Returns
Math.abs(arg)
Absolute value of arg
Math.acos(arg)
Arc cosine of arg
Math.asin(arg)
Arc sine of arg
Math.atan(arg)
Arc tangent of arg
Math.atan2(y, x)
Angle between the x axis and the point (x, y), measured counterclockwise (like polar coordinates). Note how y is passed as the first argument rather than the second.
Math.ceil(arg)
Ceiling of arg (smallest integer greater than or equal to arg)
Math.cos(arg)
Cosine of arg
Math.exp(arg)
e to arg power
Math.floor(arg)
Floor of arg (greatest integer less than or equal to arg)
Math.log(arg)
Natural log of arg (log base e of arg)
Math.max(arg1, arg2)
The greater of arg1 or arg2
Math.min(arg1, arg2)
The lesser of arg1 or arg2
Math.pow(arg1, arg2)
arg1 to the arg2 power
Math.random()
A random number in the interval [0,1]
Math.round(arg)
The result of rounding arg to the nearest integer. If the decimal portion of arg is greater than or equal to .5, it is rounded up. Otherwise, arg is rounded down.
Math.sin(arg)
Sine of arg
Math.sqrt(arg)
Square root of arg
Math.tan(arg)
Tangent of arg
There are several aspects of the Math object that need to be kept in mind. The trigonometric methods work in radians, so you need to multiply any degree measurements by p / 180 before using them. Also, because of the imprecise characteristic of floating-point operations, you might notice minor deviations from the results you expect. For example, though the sine of p is 0, the following code:
alert(Math.sin(Math.PI));

JavaScript and XML

To demonstrate JavaScript, XML, and the DOM in action, let’s use Internet Explorer 5.5 or better to load an XML document containing our employee directory and see if we can manipulate it. First, to load in the document we create an instantiation of Microsoft’s XML parser using the JScript-specific ActiveXobject. Once the object is created, we load the appropriate XML document into memory. In this case, it is the pure XML file of employee records we saw earlier without style sheets or other references.
var xmldoc = new ActiveXObject("Microsoft.XMLDOM");

xmldoc.async = false;

xmldoc.load("staff2.xml");
Once loaded, we can then use the DOM to manipulate it. For example, we can access the root element of the document (<<directory>>) using
var rootElement = xmldoc.documentElement;
then we might alert out its nodeName property as shown in this example.
<<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">>

<<html xmlns="http://www.w3.org/1999/xhtml">>

<<head>>

<<title>>XML Demo<</title>>

<<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />>

<</head>>

<<body>>

<<script type="text/jscript">>

<<!--

 var xmldoc = new ActiveXObject("Microsoft.XMLDOM");

 xmldoc.async = false;

 xmldoc.load("staff.xml");



 var rootElement = xmldoc.documentElement;

//-->>

<</script>>

<<form action="#" method="get">>

 <<input type="button" value="show node"

 onclick="alert(rootElement.nodeName);" />>

<</form>>

<</body>>

<</html>>
 
 
 
 
 
 
function deleteLastElement()

{

  var rootElement = xmldoc.documentElement;

  if (rootElement.hasChildNodes())

     rootElement.removeChild(rootElement.lastChild);

}
 
 
 
Really the only difference here is the use of the xmldoc object we created to reference the XML document rather than just plain document, which would reference the HTML Document object. Otherwise, the manipulations are the same as with HTML.
 

Javascript Image Objects

Properties of Image Objects
Property
Description
align
Indicates the alignment of the image, usually “left” or “right.”
alt
The alternative text rendering for the image as set by the alt attribute.
border
The width of the border around the image in pixels.
complete
Non-standard (but well-supported) Boolean indicating whether the image has completed loading.
height
The height of the image in pixels or as a percentage value.
hspace
The horizontal space around the image in pixels.
isMap
Boolean value indicating presence of the ismap attribute, which indicates the image is a server-side image map. The useMap property is used more often today.
longDesc
The value of the (X)HTML longdesc attribute, which provides a more verbose description for the image than the alt attribute.
lowSrc
The URL of the “low source” image as set by the lowsrc attribute. Under early browsers, this is specified by the lowsrc property.
name
The value of the name attribute for the image.
src
The URL of the image.
useMap
The URL of the client-side image map if the <img> tag has a usemap attribute.
vspace
The vertical space in pixels around the image.
width
The width of the image in pixels or as a percentage value.
The traditional Image object also supports onabort, onerror, and onload event handlers. The onabort handler is invoked when the user aborts the loading of the image, usually by clicking the browser’s Stop button. The onerror handler is fired when an error occurs during image loading. The onload handler is, of course, fired once the image has loaded. Under modern browser implementations that support (X)HTML properly, you will also find onmouseover, onmouseout, onclick, and the rest of the core events supported for Image.

Javascript The + Operator

The binary + operator adds numeric operands or concatenates string operands:

1 + 2 // => 3
"hello" + " " + "there" // => "hello there"
"1" + "2" // => "12"

When the values of both operands are numbers, or are both strings, then it is obvious
what the + operator does. In any other case, however, type conversion is necessary, and
the operation to be performed depends on the conversion performed. The conversions
rules for + give priority to string concatenation: if either of the operands is a string or
an object that converts to a string, the other operand is converted to a string and concatenation
is performed.

Javascript Recursion

Recursion is when a function calls itself. This is often useful in mathematics,
such as fi nding the nth number in the Fibonacci series (1, 2, 3, 5,
8, 13, 21…).
function fi bonacci(n) {
if ( n < 2 ) {
return 1;
} else {
return fi bonacci(n-2) + fi bonacci(n-1);
}
}
fi bonacci(5);
8
fi bonacci(10);
89

Javascript Objects as Arguments

You may want to write functions that take many arguments, some of
which are optional.
function drawElement( color, border, width, height,
left, top, zIndex) {
// Make and display an element with these variables
}
drawElement("red", 4, null, null, 100, 10);
Function signatures like this aren’t ideal for a couple of reasons:
■ It’s hard to remember the exact order of arguments.
■ You have to specify null values when you want to use the default
value for arguments in the middle of the signature.
■ Did you notice that I forgot to specify a value for zIndex? It’s hard to
count all those arguments correctly!
Passing multiple values in a single object is often a better solution:
function drawElement(options) {
// Make and display an element with the values in options
}
drawElement({
color: "red",
border: 4,
left: 100,
top: 10
});
Specifying default values is a little bit trickier with this technique. You’ll
need to create an object holding all the defaults and merge it with the
options object.

Javascript search

search(regexp)
The search() method is the same as indexOf() except that it takes a
regular expression pattern instead of a substring. It also returns -1 if the
pattern isn’t found.
"hello world".search(/[aeiou]/); // Find the fi rst vowel
1
"hello world".search(/\d/); // Find the fi rst digit
-1
match(regexp)
The match() method returns an array containing all the substrings
matching the regular expression and its subpatterns. Unlike the other
search-and-replace methods, it returns null if the pattern doesn’t match.
Here are some simple examples, but I’ll cover this function more in
Chapter 8:
// Find all the vowels
"hello world".match(/[aeiou]/g);
["e", "o", "o"]
// Find "world" regardless of capitalization
"hElLo WoRlD".match(/world/i);
["WoRlD"]
replace(pattern, replacement)
The replace() method works like match() except that it returns a string
with all instances of pattern replaced by the string replacement.
// Remove all non-numeric characters from a phone number
"(310) 555-9876".replace(/\D/g, "");

JavaScript Popups

<head>
<script type="text/javascript">

function testPopup() {
window.open( "http://www.google.com/" )
}

</script>
</head>
<body>
<form>
<input type="button" onClick="testPopup()" value="Click">
</form>
</body>


OpenNewWindow =window.open('contact.html','help','toolbar=no,
location=0,directories=no,status=yes,menubar
=0,scrollbars=yes,resizable=yes,
width=300,height=350')





JavaScript Window.Open Arguments


When you open a window, you can set its URL, name, size, buttons, and other attributes, such as whether or not the window can be resized. The basic syntax of this method is


window.open(url, name, features, replace)


where

url is a URL that indicates the document to load into the window.

name is the name for the window (which is useful for referencing later on using the target attribute of HTML links).features is a comma-delimited string that lists the features of the window.

replace is an optional Boolean value (true or false) that indicates if the URL specified should replace the window’s contents or not. This would apply to a window that was already created.

An example of this method is

secondwindow = open("http://www.yahoo.com", "yahoo", "height=300,width=200,

 scrollbars=yes");



<a href="http://www.google.com" target="_blank">Go to Google</a>

Javascript Making a simple MouseOver

<a href="http://www.cit.cornell.edu"
onMouseOver="document.logo.src='family.gif ' ; "
onMouseOut ="document.logo.src='harry.gif ' ; " >
<img name="logo" src="harry.gif " border=0></a>


The onMouseOver and onMouseOut attributes are “Event Handlers” that tell the browser what
code to execute when the events occur. You can make it so that the mouseover affects another image on
the page by changing the name of the image accordingly in the event handler code.

We can use a MouseOver to animate a still image when the
mouse rolls over it. In your class files folder you have two images, logoscroll.gif and logostill.gif which
can be used to create this effect.

Javascript String Constructor

String is the built-in object corresponding to the primitive string data type. It contains a very large number of methods for string manipulation and examination, substring extraction, and even conversion of strings to marked-up HTML, though unfortunately not standards-oriented XHTML.

The String() constructor takes an optional argument that specifies its initial value:

var s = new String();

var headline = new String("Dewey Defeats Truman");


Because you can invoke String methods on primitive strings, programmers rarely create String objects in practice.

The only property of String is length, which indicates the number of characters in the string.

var s = "String fun in JavaScript";

var strlen = s.length;

// strlen is set to 24


The length property is automatically updated when the string changes and cannot be set by the programmer. In fact there is no way to manipulate a string directly. That is, String methods do not operate on their data “in place.” Any method that would change the value of the string, returns a string containing the result. If you want to change the value of the string, you must set the string equal to the result of the operation. For example, converting a string to uppercase with the toUpperCase() method would require the following syntax:

var s = "abc";

s = s.toUpperCase();

// s is now "ABC"
Invoking s.toUpperCase() without setting s equal to its result does not change the value of s. The following does not modify s:

var s = "abc";

s.toUpperCase();

// s is still "abc"
Other simple string manipulation methods such as toLowerCase() work in the same way; forgetting this fact is a common mistake made by new JavaScript programmers.

JavaScript String Split Function

split()

The split() method splits (for lack of a better word) a string up into substrings and returns them in an array. It accepts a string or regular expression argument containing the delimiter at which the string will be broken.

<script type="text/javascript">
var testString = "It is very nice script";

var testSplitResult = testString.split(" ");

for(i = 0; i < testSplitResult.length; i++){
    document.write("<br /> Element " + i + " = " + testSplitResult[i]);
}
</script>

JavaScript Redirect

<script type="text/javascript">

window.location = "http://www.yoursite.com/"

</script>

JavaScript System Dialogs alert(),confirm(),prompt()

The browser is capable of invoking system dialogs to display to the user through the alert(),
confirm(), and prompt() methods. These dialogs are not related to the web page being displayed
in the browser and do not contain HTML. Their appearance is determined by operating system and/
or browser settings rather than CSS. Additionally, each of these dialogs is synchronous and modal,
meaning code execution stops when a dialog is displayed, and resumes
after it has been dismissed.

The alert() method has been used throughout this book. It simply
accepts a string to display to the user. When alert() is called, a
system message box displays the specifi ed text to the user, followed by
a single OK button.

Alert dialogs are typically used when users must be made aware of something that they have no
control over, such as an error. A user’s only choice is to dismiss the dialog after reading the message.
The second type of dialog is invoked by calling confirm(). A confi rm dialog looks similar to an
alert dialog in that it displays a message to the user. The main difference between the two is the

To determine if the user clicked OK or Cancel, the confirm() method
returns a Boolean value: true if OK was clicked, or false if Cancel
was clicked or the dialog box was closed by clicking the X in the
corner. Typical usage of a confi rm dialog looks like this:

if (confirm(“Are you sure?”)) {
alert(“I’m so glad you’re sure! “);
} else {
alert(“I’m sorry to hear you’re not sure. “);
}

If the OK button is clicked, prompt() returns the value in the text box; if Cancel is clicked or the
dialog is otherwise closed without clicking OK, the function returns null. Here’s an example:

var result = prompt(“What is your name? “, “”);
if (result !== null) {
alert(“Welcome, “ + result);
}

JavaScript Variables

Variables store a value you can refer to later in the script. Variable names
can be nearly any valid identifi er. A JavaScript identifi er is a word that
contains only letters, numbers, $, and _, and that doesn’t start with a
number.
Variables are a great demonstration of how statements and expressions
can be combined. You use a variable declaration statement to create a
variable.

var myVariable;

If you already have a variable, you can use a variable assignment expression
to assign it a value.

myVariable = 42;
42
You can combine a variable declaration with an assignment expression.
var myVariable = 42;
You can also string together several variable declarations with commas.
Don’t forget the commas, though! Leaving off a comma can have the
unintended side effect of declaring a global variable when you don’t
mean to do that.var variable1 = 4,
variable2 = 8,
variable3 = 15;

JavaScript has a relatively small number of built-in data types, including
these common types:
var myNumber = 42;
var myString = "A string of text";
var myBoolean = true;
var myArray = [myNumber, myString, myBoolean];

JavaScript Alert

The JavaScript alert is a dialogue box that pops up and takes the focus away from the current window and forces the web browser to read the message.


1.
<form>
<input type="button" onclick=
"alert('Are you sure you want to call')"
value="See">
</form>


2.
function myFunc() {
alert("executing myFunc!");
return true;
}

3.

for (var i = 0; i < 10; i++) {
var link = document.createElement("a");
link.innerHTML = "Link " + i;
link.href = "#";
link.onclick = function() {
alert("This is link " + i);
return false;
};
document.body.appendChild(link);
}

Web Application with PHP


PHP embedded in HTML

<html>
<head><title>Example 1</title></head>
<body>
<?php
/* If it is April 1st, we show a quote */
if (date('md' == '0401')) {
echo 'A bookstore is one of the only pieces of evidence we have '.
'that people are still thinking. <i>Jerry Seinfeld</i>';
} else {
echo 'Good morning!';
}
?>
</body>
</html>

The line
<?php
begins the PHP section embedded into the HTML code; the
line
?>
ends the PHP section. Notice that the code uses echo
to send the output.
When the text is so simple, the echo
statements are acceptable.

Creating A Function In Javascript

The basic structure of a function looks like this:

function functionName() {
// the JavaScript you want to run
}

The keyword function lets the JavaScript interpreter know you’re creating a function—
it’s similar to how you use if to begin an if/else statement or var to create a variable.

function printToday()
{
var today = new Date();
document.write(today.toDateString());
}

The function’s name is printToday. It has just two lines of JavaScript code that retrieve
the current date, convert the date to a format we can understand

Javascript Do While Loops

There’s another, less common type of loop, known as a do/while loop. This type of
loop works nearly identically to a while loop. Its basic structure looks like this:

do {
// javascript to repeat
} while (condition) ;

do {
var luckyNumber = prompt('What is your lucky number?','');
luckyNumber = parseInt(luckyNumber, 10);
} while (isNaN(luckyNumber));

Save this file and preview it in a web browser. Try typing text and other nonnumeric
symbols in the prompt dialog box. That annoying dialog box continues
to appear until you actually type a number.

Javascript For Loops

JavaScript offers another type of loop, called a for loop, that’s a little more compact
(and a little more confusing). For loops are usually used for repeating a series of
steps a certain number of times, so they often involve some kind of counter variable,
a conditional test, and a way of changing the counter variable. In many cases,
a for loop can achieve the same thing as a while loop, with fewer lines of code. For
example.

for (var num=1; num<=100; num++) {
document.write('Number ' + num + '<br>');
}


var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday','Friday', 'Saturday', 'Sunday'];
for (var i=0; i<days.length; i++) {
document.write(days[i] + ', ');
}

Since for loops provide an easy way to repeat a series of steps a set number of times,
they work really well for working through the elements of an array. The while loop
in Figure 3-5, which writes each item in an array to the page, can be rewritten using
a for loop,

Javascript While Loops

A while loop repeats a chunk of code as long as a particular condition is true; in other
words, while the condition is true. The basic structure of a while loop is this:

while (condition) {
// javascript to repeat
}

The first line introduces the while statement. As with a conditional statement, you
place a condition between the set of parentheses that follow the keyword while.

Say you want to print the numbers 1 to 5 on a page. One possible way to do that is
like this:

document.write('Number 1 <br>');
document.write('Number 2 <br>');
document.write('Number 3 <br>');
document.write('Number 4 <br>');
document.write('Number 5 <br>');

Notice that each line of code is nearly identical—only the number changes from line
to line. In this situation, a loop provides a more efficient way to achieve the same goal:

var num = 1;
while (num <= 5) {
document.write('Number ' + num + '<br>');
num += 1;
}

Javascript Array

You can access the contents of a simple variable just by using the variable’s name.
For example, alert(lastName) opens an alert box with the value stored in the variable
lastName. However, because an array can hold more than one value, you can’t just
use its name alone to access the items it contains. A unique number, called an index,
indicates the position of each item in an array. To access a particular item in an array,
you use that item’s index number. For example, say you’ve created an array with
abbreviations for the days of the week, and want to open an alert box that displayed
the first item.

var days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'];
alert(days[0]);


Javascript Object Type


Objects are
created by using the new operator followed by the name of the object type to create. Developers
create their own objects by creating instances of the Object type and adding properties and/or
methods to it, as shown here:

var o = new Object();

Each Object instance has the following properties and methods:
constructor — The function that was used to create the object. In the previous example,
the constructor is the Object() function.

hasOwnProperty(propertyName) — Indicates if the given property exists on the object
instance (not on the prototype). The property name must be specifi ed as a string (for
example, o.hasOwnProperty(“name”)).

isPrototypeOf(object) — Determines if the object is a prototype of another object.

propertyIsEnumerable(propertyName) — Indicates if the given property can be
enumerated using the for-in statement (discussed later in this chapter). As with
hasOwnProperty(), the property name must be a string.

toLocaleString() — Returns a string representation of the object that is appropriate for
the locale of execution environment.

toString() — Returns a string representation of the object.

valueOf() — Returns a string, number, or Boolean equivalent of the object. It often
returns the same value as toString().

HTML5 Constraint Validation API

HTML5 introduces the ability for browsers to validate data in forms before submitting to the
server. This capability enables basic validation even when JavaScript is unavailable or fails to load.
The browser itself handles performing the validation based on rules in the code and then displays
appropriate error messages on its own (without needing additional JavaScript). Of course, this
functionality works only in browsers that support this part of HTML5, including Firefox 4+,
Safari 5+, Chrome, and Opera 10+.
Validation is applied to a form fi eld only under certain conditions. You can use HTML markup to
specify constraints on a particular fi eld that will result in the browser automatically performing
form validation.

Required Fields
The fi rst condition is when a form fi eld has a required attribute, as in this example:

<input type=”text” name=”username” required>

Any field marked as required must have a value in order for the form to be submitted. This
attribute applies to <input>, <textarea>, and <select> fi elds (Opera through version 11 doesn’t
support required on <select>). You can check to see if a form fi eld is required in JavaScript by
using the corresponding required property on the element:
var isUsernameRequired = document.forms[0].elements[“username”].required;
You can also test to see if the browser supports the required attribute using this code snippet:
var isRequiredSupported = “required” in document.createElement(“input”);
This code uses simple feature detection to determine if the property required exists on a newly
created <input> element.

Keep in mind that different browsers behave differently when a form fi eld is required. Firefox 4 and
Opera 11 prevent the form from submitting and pop up a help box beneath the fi eld, while Safari (as
of version 5) and Chrome (as of version 9) do nothing and don’t prevent the form from submitting.

Javascript Event Object

Properties

Different types of events have different properties, which you’ll learn
about later in the chapter. Here are a few properties common to all standard
Event objects:
■ type The type of the event, like “click,” “load,” or “keypress.”
■ target The element that originally dispatched the event. This may not
be the same as the element to which the event handler is attached.
■ currentTarget The element to which you attached the event handler.
In most cases, it is synonymous with the this keyword. If you change
the context of the event handler with call() or apply(), you can still
access the element with currentTarget.
■ eventPhase A number that indicates whether the event is currently
capturing (1), bubbling (3), or at the target element (2). Find out more
information in the “Event Bubbling and Capturing” section later in this
chapter.
■ timeStamp A number in seconds that represents the time at which the
event occurred.


<a id="link" href="http://www.google.com">Don't go to
Google</a>
var link = document.getElementById("link");
link.addEventListener("click", dontFollowLink, false);
function dontFollowLink(event) {
alert("Not going to " + this.href);
event.preventDefault();

}


In Internet Explorer, the Event object isn’t available as an argument
of the handler. Instead, it’s a property of window. To write crossbrowser
DOM Level 0 code, look for the Event object in both places.
function handler(event) {
event = event || window.event;
}

Javascript Cookies

Cookies are small strings that let you store data across page views and
sessions. These are some common uses of cookies:
1. Keeping track of whether the user has logged in to your site
2. Remembering that a user has visited a page before
3. Differentiating between fi rst-time visitors and repeat visitors
Cookies are also sent to the server with every page request. That’s how
the server knows whether the user is logged in. Because cookies add data
to the request and therefore increase the size of the request, cookie data
is limited to 4KB.
The window.document object has a funny little property called cookie.
You can use that object to read and set cookie data.
Setting Cookies
To set a cookie, just assign the name and value to document.cookie
in the following format:
document.cookie = "name=value";
You can set only one cookie at a time, but assigning another value to
document.cookie doesn’t overwrite the previous cookies, unless one of
them shares the same name. You can continue to assign name/value pairs
to document.cookie until you hit the 4KB limit enforced by the browser.
// Adding another cookie
document.cookie = "anotherName=anotherValue";
You should always pass the value part of the string through
encodeURIComponent() to make sure it doesn’t contain any illegal
characters such as spaces, commas, and semicolons.
var cookieValue = "encoded value";
document.cookie = "thirdCookie=" +
encodeURIComponent(cookieValue);
You can also set the following optional parameters that affect the



// This secure cookie will last a year
document.cookie = "name=value;max-age=" + (60*60*24*365) +
";secure;";

You’ll have to use your string manipulation skills to extract a single
cookie’s value from this string. Regular expressions come in handy here.

function getCookie(name) {
// Get each individual cookie by splitting
// on semicolons and possible spaces
var cookies = document.cookie.split(/;\s*/);
// Make a regular expression to match the name
// and value in a subpattern
var pattern = new RegExp("\\b" + name + "=(.*)");
// Check each cookie until you fi nd a match
for (var i = 0, l = cookies.length; i < l; i++) {
var match = cookies[i].match(pattern);
if (match) {
return decodeURIComponent(match[1]);
}
}
}

Javascript forEach

Looping over arrays using functions is increasingly common, especially in
certain libraries. Modern browsers support the forEach() method, but
you can also build your own.
function arrayForEach(array, loopFunc) {
// If the browser support forEach, use it because
// it will be faster
if ("forEach" in array) {
return array.forEach(loopFunc);

// Otherwise, loop over the array and pass in
// the array values to the loop function
} else {
for (var i = 0, l = array.length; i < l; i++) {
loopFunc(array[i], i, array);
}
return array;
}
}
function doSomeMath(num) {
console.log(num * 10 - 5);
}
arrayForEach([1,2,3], doSomeMath);



5
15
25

Javascript Creating Arrays

The best way to create a new array is with the array literal syntax ([]),
but the array constructor function is available too. If you pass a single
number value to the constructor function, you get an array fi lled with
that many undefi ned values.
var myArray = [];
var myFilledArray = new Array(4);
myFilledArray;
[undefi ned, undefi ned, undefi ned, undefi ned]
Properties
Like strings, arrays have one built-in property: length. This property is
equal to the number greater than the last index in the array. This is true
even if you skip some indices.
["a", 1, true, null].length;
4
var myArray = [];
myArray.length;
0
myArray[99] = 1;
1
myArray.length;
100
The new length of myArray is 100 even though it contains only one value
at index 99. All the other values are undefined.

JavaScript String Length

The length  returns the number of characters that are in a string, using
an integer.


<script type="text/javascript">
var testString = "11111";
var length = testString.length;
document.write("The string length is: " + length);

</script>



output:-

The string length is: 5

Comparing strings in JavaScript


<script type="text/javascript">
var username = "test";
if(username == "test")
    document.write("Welcome");
else
    document.write("Access Denied!");
document.write("<br /><br />Try again?<br /><br />");


</script>

While '14' == 14 is true (because by converting either the left side
value to a number or converting the right side value to a text string
will result in both being the same) '123' === 123 is false since one
value is a text string and the other is a number.

The === operator does the same thing with one minor difference. This
operator does not convert data from one type to another.

JavaScript String indexOf

var p = navigator.platform;
system.win = p.indexOf(“Win”) == 0;
system.mac = p.indexOf(“Mac”) == 0;
system.x11 = (p.indexOf(“X11”) == 0) || (p.indexOf(“Linux”) == 0);


This code uses the indexOf() method to look at the beginning of the platform string. To detect
Windows, the platform-detection code simply looks for the string “Win” at the beginning of the
platform string (covers both “Win32” and “Win64”). Testing for a Mac platform is done in the same
way to accommodate both “MacPPC” and “MacIntel”. The test for Unix looks for both “X11” and
“Linux” at the beginning of the platform string to future-proof this code against other variants.

<script type="text/javascript">
var mURL = "http://www.google.com/";
var mPosition = mURL.indexOf("www");

document.write("The position of www  =  " + mPosition); 
</script>

Why Use Sitemaps?

It is important to use Sitemaps because they help your visitors quickly get to the information
they need, and they help web spiders find your site’s links.
There is no universal Sitemap rule that you can apply to every site. Understanding
different Sitemap options should help you identify the right type for each situation. The
following subsections discuss some of the reasons for using Sitemaps.

Crawl augmentation
Although web spiders are continuously improving, they are far from perfect. Search
engines have no problems admitting this.

Poor linking site structure
Not all sites are created equal. Sites with poor linking structures tend to index poorly.
Orphan pages, deep links, and search engine traps are culprits of poor site indexing.
The use of Sitemaps can alleviate these situations, at least temporarily, to give you
enough time to fix the root of the problem.

Crawling frequency
One of the biggest benefits of using Sitemaps is in timely crawls or recrawls of your site
(or just specific pages). XML Sitemap documents let you tell crawlers how often they
should read each page.
Sites using Sitemaps tend to be crawled faster on Yahoo! and Google. It takes Google
and Yahoo! minutes to respond to Sitemap submissions or resubmissions. This can be
very helpful for news sites, e-commerce sites, blogs, and any other sites that are constantly
updating or adding new content.

AdSense Earnings

The Google ads you are able to display on your content pages can be either cost-per-click
(CPC) or cost-per-1000-impressions (CPM) ads, while AdSense for search results pages
show exclusively CPC ads. This means that advertisers pay either when users click on
ads, or when the advertiser’s ad is shown on your site. You’ll receive a portion of the
amount paid for either activity on your website. Although we don’t disclose the exact
revenue share, our goal is to enable publishers to make as much or more than they could
with other advertising networks.

Typically, Google sends checks about one month behind if your earnings pass Google’s
payment threshold ($10 in the United States). You are responsible for paying any taxes
as required in your country. Let’s look at example earnings you can make with AdSense.
Suppose you have a site that shows 1,000 AdSense impressions per day. Assuming that
your CTR is at 1% and that the average click worth is $0.10, we get the following:
Daily AdSense Earnings =
1000 (impressions) × 0.01 (CTR) × 0.10 (click worth)
= $1

So, if you have a busy site, you can do the math and see what you can earn. It sounds
pretty simple, but to make it work you need to put in the time to create good content.
A lot depends on your visitor levels as well as how you integrate AdSense within your
site(s).

Competitor Research and Analysis

Competitor research and analysis may seem like a copycat activity, but it is not (at least
not entirely). It is about understanding what your competitors are doing. It is about
examining their keyword and linking strategies while realizing their current strengths
and weaknesses. The bottom line is that you are trying to understand what is making
your competitors rank.
This activity may comprise elements of emulation, but what you are really trying to do
is be better than your competition. Being better (in a general sense) means providing a
site with more value and better perception. In an SEO sense, it means understanding
all the things that make your competitors rank.
When learning about your competition, it is good to examine their past and present
activities, as well as implement ways to track their future activities. Although many
tools are available for you to use to learn about your competition, for most of your work
you can get by with the free tools that are available. This chapter emphasizes the free
tools and research that you can use in your work.

Finding Your Competition
Before you can analyze your competitors, you need to know who your competitors are.
How do you find your biggest competitors? One way to do this is to find sites that rank
for your targeted keywords. The sites that sell or provide products and services similar
to yours are your competitors.
There is a catch if you’re relying only on keywords, though. How do you know whether
you are targeting the right keywords? What if you miss important keywords? You may
be starting off in the wrong direction. This makes it all the more important to do your
keyword research properly. No tool or activity will ever be perfect. You have to start
somewhere.

Link Building

There are countless opportunities for link building. Everything starts on your site. Your
site should make it easy and intuitive for anyone wanting to link to it. To increase your
chances of people linking to your site, you need to provide something of value.
Basic Elements
The following subsections talk about the rudimentary elements that all sites need to
consider.
Take out the guesswork
Take out the guesswork for your web visitors by providing the HTML code fragment(s)
for people to link to your site. Create “Link to Us” and “Tell a Friend” links. Most CMS
software includes prebuilt forms for handling these simple concepts.

Run a daily, weekly, or monthly email newsletter
Running your own newsletter provides several benefits. First, you get to remind your
existing visitors of your new offerings, whether it is content, products, or services. Plus,
the recipients of your newsletter are likely to forward it to people they know if they find
your newsletter interesting.

Provide registered services
Many sites offer free and members-only content. This model offers several benefits. If
your free content is already great, many of your visitors will also be interested in your
members-only content. The idea is that the content that is provided to members only
is of even greater quality than the public content. Many sites charge for members-only
content. Providing registered services helps you build up the email lists that you can

JavaScript getElementById

getElementById() is a method of document object, it gets the tag element with the value "id" in its ID attribute.

To reference in a JS script to a HTML tag through its ID, use the following syntax:

    document.getElementById("id")

So even though the Internet Explorer JavaScript engine uses a mark-and-sweep
implementation, any COM objects that are accessed in JavaScript still use reference counting,
meaning circular references are still a problem when COM objects are involved. The following
simple example demonstrates a circular reference with a COM object:

var element = document.getElementById(“some_element”);
var myObject = new Object();
myObject.element = element;
element.someObject = myObject;

This example sets up a circular reference between a DOM element (element) and a native JavaScript
object (myObject). The myObject variable has a property called element that points to element,
and the element variable has a property called someObject that points back to myObject. Because
of this circular reference, the memory for the DOM element will never be reclaimed even if it is
removed from the page.

<script type="text/javascript">
function testEmpty(){
 var myTextField = document.getElementById('myTxt');
 if(myTxtField.value != "")
  alert("entered: " + myTxtField.value)
 else
  alert("please enter some text?")  
}
</script>
<input type='text' id='myTxt' />
<input type='button' onclick='testEmpty()' value='Checked' />

The argument that getElementById requires is the id of the HTML element you wish to utilize.

JavaScript Objects

Each Object instance has the following properties and methods:
constructor — The function that was used to create the object. In the previous example,
the constructor is the Object() function.

hasOwnProperty(propertyName) — Indicates if the given property exists on the object
instance (not on the prototype). The property name must be specifi ed as a string (for
example, dataObj.hasOwnProperty(“name”)).

isPrototypeOf(object) — Determines if the object is a prototype of another object.

propertyIsEnumerable(propertyName) — Indicates if the given property can be
enumerated using the for-in statement . As with
hasOwnProperty(), the property name must be a string.

toLocaleString() — Returns a string representation of the object that is appropriate for
the locale of execution environment.

toString() — Returns a string representation of the object.

valueOf() — Returns a string, number, or Boolean equivalent of the object. It often
returns the same value as toString().


A new instance of an object:

dataObj=new Object();

dataObj.firstname="Jonti";
dataObj.lastname="Leff";
dataObj.age=40;
dataObj.eyecolor="red";


JavaScript and HTML DOM

WORKING WITH THE DOM

In many cases, working with the DOM is fairly straightforward, making it easy to re-create with
JavaScript what normally would be created using HTML code.


 
Dynamic Scripts
The <script> element is used to insert JavaScript code into the page, either using by the src attribute
to include an external fi le or by including text inside the element itself. Dynamic scripts are those
that don’t exist when the page is loaded but are included later by using the DOM. As with the
HTML element, there are two ways to do this: pulling in an external fi le or inserting text directly.
Dynamically loading an external JavaScript fi le works as you would expect. Consider the following
<script> element:

<script type=”text/javascript” src=”client.js”></script>
This <script> element includes the text for the Chapter 9 client-detection script. The DOM code to
create this node is as follows:
var script = document.createElement(“script”);
script.type = “text/javascript”;
script.src = “client.js”;
document.body.appendChild(script);