Home > Articles > Web Development > Ajax and JavaScript

This chapter is from the book

Setting Up a Web Development Environment

With the brief introduction to dynamic web programming out of the way, it is time to cut to the chase and get your development environment ready to write jQuery and JavaScript.

The development environment can make all the difference when you are writing jQuery and JavaScript projects. The development environment should have these following components:

  • Easy to Use IDE—The IDE provides text editors that allow you to modify your code in the simplest manner possible. Choose an IDE that you feel comfortable with and that is extensible to support HTML, CSS, JavaScript, jQuery, and AngularJS.
  • Development Web Server—You should never develop directly on a live web server (although most of us have done it at one point or another). A test development web server is required to test out scripts and interactions.
  • Development Web Browser(s)—Again, you should initially develop to the browser that you are most comfortable with or that will be the most commonly used.

For the purposes of this book, we have chosen to use Eclipse for the IDE and Node.js for the development web server. These technologies are very easy to set up, configure, and get going with. They also integrate well with each other and are easily extended. The following sections take you through the process of setting up Node.js and Eclipse for JavaScript development.

Setting Up Node.js

Node.js is a JavaScript platform based on Google Chrome’s V8 engine that enables you to run JavaScript applications outside of a web browser. It is an extremely powerful tool, but this book covers only the basics of using it as the web server to support your web application examples.

To install and use Node.js, you need to perform the following steps:

  1. Go to the following URL and click INSTALL. This will download an installable package to your system. For Windows boxes, you will get an .MSI file; for Macs, you will get a .PKG file; and for Linux boxes, you can get a .tar.gz file.

  2. Install the package. For Windows and Macs, simply install the package file. For Linux, go to the following location for instructions on installing using a package manager:

  3. Open a terminal or console window.
  4. Type node to launch the Node.js JavaScript shell, and you should see a > prompt. The Node.js shell provides the capability to execute JavaScript commands directly on the underlying JavaScript engine.
  5. If the node application is not found, you need to add the path to the node binary directory to the PATH for your development system (this process is different for each different platform). The binary directory is typically /usr/local/bin/ on Macs and Linux boxes. On Windows, the binary directory will be in the <install>/bin folder, where <install> is the location you specified during the installation process.
  6. Then you get to the > prompt. Type the following command and verify that Hello is printed on the screen, as shown in Figure 1.6:

    FIGURE 1.6

    FIGURE 1.6 Starting and using the Node.js command prompt.

  7. Use the following command to exit the Node.js prompt:


You have now successfully installed and configured Node.js.

Configuring Eclipse as a Web Development IDE

The IDE is the most important aspect when developing with JavaScript. An IDE integrates the various tasks required to write web applications into a single interface. In reality, you could use any text editor to write HTML, CSS, JavaScript, and jQuery code. However, you will find it much more productive and easy to use a good IDE.

We chose Eclipse for this book because it is a great general IDE that is easy to configure and set up. You can use your own IDE if you would rather; however, this might be a good chance to try a different IDE if you are unfamiliar with Eclipse.

Use the following steps to download, install, and configure Eclipse:

  1. Install a Java JRE or JDK. For this book, we downloaded and installed the Java SE Development Kit 8 from the following location:


  2. Download and extract Eclipse. The location you extract the Eclipse files to will be the installation location. For this book, we installed the Luna version Eclipse IDE for Java Developers from the following location:


  3. Start Eclipse by double-clicking the Eclipse executable file.
  4. After Eclipse has loaded, install the Node.js plug-in for Eclipse by selecting Help, Eclipse Marketplace from the main menu. Then type nodeclipse into the Find box and click Install to install the package, as shown in Figure 1.7. You will need to accept the license agreement as part of the install process.

    FIGURE 1.7

    FIGURE 1.7 Installing the Nodeclipse plug-in for Eclipse.

  5. After the Nodeclipese plug-in is installed, install the HTML Editor plug-in by selecting Help, Eclipse Marketplace from the main menu. Then type html editor into the Find box and click Install to install the package, as shown in Figure 1.8. You will need to accept the license agreement as part of the install process.

    FIGURE 1.8

    FIGURE 1.8 Installing the HTML Editor plug-in for Eclipse.

  6. Restart Eclipse to enable the new plug-ins.
  7. Verify that the .js extensions uses Nodeclipse and .html extensions use HTML Editor as their default editors. To do this, select Window, Preferences, and then select General, Editors, File Associations and click the file types to see the associated editors, as shown in Figure 1.9.

    FIGURE 1.9

    FIGURE 1.9 Setting default editors for file types in Eclipse.

  8. Set the path to the Node.js executable by selecting Window, Preferences and then selecting Nodeclipse in the navigation pane. The Node.js path option is toward the top of the options.
  9. Create a project for this book by selecting File, New, Project to launch the New Project Wizard. Then select Node, Node.js Project. Click Next and type in the name of the project; for example, LearningJavaScript. Then click Finish to create the project.
  10. Now we’ll validate that things work by creating and running a JavaScript Application from Eclipse. Select the new project and then select File, New JavaScript File from the main menu. Name the file first.js and click Finish to create the file.
  11. Type the following line of code into the file and save it:

  12. Double-click to the left of line number 2 so that a small circle appears, noting that a breakpoint has been set.
  13. Select Run, Run As, Node Application. You should see the word “Hello” printed to the Console window, as shown in Figure 1.10.

    FIGURE 1.10

    FIGURE 1.10 Running a JavaScript application in Eclipse.

Eclipse is now set up and ready for you to begin developing JavaScript.

Creating an Express Web Server Using Node.js

Node.js is a very modular platform, meaning that Node.js itself provides a very efficient and extensible framework, and external modules are utilized for much of the needed functionality. Consequently, Node.js provides a very nice interface to add and manage these external modules.

Express is one of these modules. The Express module provides a simple-to-implement web server with a robust feature set, such as static files, routes, cookies, request parsing, and error handling.

The best way to use Node.js as the web server for your web development is to utilize the Express module. In the following exercise, you build a Node.js/Express web server and use it to serve static files.

Use the following steps to build and test a Node.js/Express web server capable of supporting static files and server-side scripting:

  1. Open a console prompt and navigate to the location where you created the project folder for this book. If you don’t know the path, right-click the project in Eclipse and select Properties from the menu. Then select Resource, and the full path to the project folder is shown in the Location field to the right.
  2. From a console prompt in the project folder, execute the following command, as shown in Figure 1.11. This command will install the Express module version 4.6.1 for Node.js into a subfolder named node_modules:

    npm install express@4.6.1

    FIGURE 1.11

    FIGURE 1.11 Installing the Express npm module for Node.js from a console prompt.

  3. Execute the following command to install the body-parser module for Node.js. This module makes it possible to parse the query parameters and body from HTTP GET and POST requests. This command will install the body-parser module version 1.6.5 for Node.js into a subfolder named node_modules:

    npm install body-parser@1.6.5

  4. Go back to Eclipse, right-click the project, and select Refresh. You should see the node_modules folder with body-parser and express subfolders.
  5. Create a file named server.js in the root of your project directory, place the contents from Listing 1.5 inside of it, and save it. This is a basic Node.js/Express web server that will service static files using the root of your project directory as the website root location.
  6. Verify that your Node.js web server will run correctly. Start the web server by right-clicking the server.js file and selecting Run As, Node Application from the menu. The Console window, shown in Figure 1.12, should show that the server.js file is running and provide a red box to stop the server. If you are running multiple applications in Eclipse, you can click the Console Select button to select a specific console, as shown in Figure 1.12.

    FIGURE 1.12

    FIGURE 1.12 Running a JavaScript application in Eclipse.

  7. Hit the server from a web browser at the following address. Because the web server is servicing static files using the ./ path, the actual contents of the server.js file should be displayed in the browser:


  8. Stop the web server by clicking the red box in the Console window.

You have now successfully set up a Node.js/Express web server in Eclipse. You will use this web server for most of the examples in the book. A few of the lessons require AJAX interaction, and a separate server will be created for those lessons.

LISTING 1.5 server.js Creating a Basic Node.js/Express Web Server

01 var express = require('express');
02 var app = express();
03 app.use('/', express.static('./'));
04 app.listen(80);

Adding HTML

The first step is to create a simple web page that has an HTML element that you can stylize and manipulate. Use the following steps in the editor to create the HTML document that you will use as your base:

  1. Create a folder named lesson01 in your project.
  2. Right-click the lesson01 folder that you created.
  3. Select New, File from the pop-up menu.
  4. Name the file first.html and click OK. A blank document should be opened up for you.
  5. Type in the following HTML code. Don’t worry if you are not too familiar with HTML; you’ll learn enough to use it a bit later in the book:

    <!DOCTYPE html>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <span>Click Me</span>
  6. Save the file.
  7. Open the following URL in your web browser and you should see the text “Click Me” appear:


That’s it. All the basic HTML elements are now in place. In the next section, you stylize the <span> element so that Click Me looks more like a button.

Adding CSS

The simple text rendered by the browser is pretty plain, but that problem can quickly be solved by adding a CSS style. In this section, you use CSS to make the text appear more like a button.

Use the following steps to add the CSS style to the <span> element. For reference, the style changes you make in these steps are shown in the final script in Listing 1.6:

  1. Add the following code inside the <head> tags of the web page to include a CSS <style> element for all <span> elements:

  2. Add the following property setting to the span style to change the background of the text to a dark blue color:

    background-color: #0066AA;
  3. Add the following property settings to the span style to change the font color to white and the font to bold:

    color: #FFFFFF;
    font-weight: bold;
  4. Add the following property settings to the span style to add a border around the span text:

    border-color: #C0C0C0;
    border:2px solid;
    padding: 3px;
  5. Add the following property settings to the span style to set an absolute position for the span element:

  6. Save the file.
  7. Open the following URL in your web browser, and you should see the stylized text Click Me appear, as shown in Figure 1.13:


FIGURE 1.13 <span> element stylized to look like a button.

Writing a Dynamic Script

Now that the HTML is stylized the way you want it, you can begin adding dynamic interactions. In this section, you add a link to a hosted jQuery library so that you will be able to use jQuery, and then you link the browser mouse event mouseover to a JavaScript function that moves the text.

Follow these steps to add the jQuery and JavaScript interactions to your web page:

  1. Change the <span> element to include an ID so that you can reference it, and also add a handler for the mouseover event, as shown in line 30 of Listing 1.6:

    <span id="elusiveText" onmouseover="moveIt()">Click Me</span>
  2. Add the following line of code to the <head> tag, as shown in line 6 of Listing 1.6. This loads the jQuery library from a hosted source:

    <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
  3. Add the following JavaScript function to the <head>, as shown in lines 6–13 of Listing 1.6. This function creates an array of coordinate values from 10 to 350, then randomly sets the top and left CSS properties of the span element each time the mouse is moved over it:

    function moveIt(){
      var coords = new Array(10,50,100,130,175,225,260,300,320,350);
      var x = coords[Math.floor((Math.random()*10))];
      var y = coords[Math.floor((Math.random()*10))];
      $("#elusiveText").css({"top": y + "px", "left": x + "px"})
  4. Save the file.
  5. Open the following URL in your web browser, and you should see the stylized text Click Me appear, as shown in Figure 1.13:

  6. Now try to click the Click Me button. The button should move each time the mouse is over it, making it impossible to click it.
  7. Find someone who annoys you, and ask them to click the button.

LISTING 1.6 A Simple Interactive jQuery and JavaScript Web Page

01 <!DOCTYPE html>
02 <html>
03   <head>
04     <meta charset="utf-8" />
05     <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
06     <script>
07       function moveIt(){
08         var coords = new Array(10,50,100,130,175,225,260,300,320,350);
09         var x = coords[Math.floor((Math.random()*10))];
10         var y = coords[Math.floor((Math.random()*10))];
11         $("#elusiveText").css({"top": x + "px", "left": y + "px"})
12       }
13     </script>
14     <style>
15       span{
16         background-color: #0066AA;
17         color: #FFFFFF;
18         font-weight: bold;
19         border-color: #C0C0C0;
20         border:2px solid;
21         border-radius:5px;
22         padding: 3px;
23         position:absolute;
24         top:150px;
25         left:100px;
26       }
27     </style>
28   </head>
29   <body>
30     <span id="elusiveText" onmouseover="moveIt()">Click Me</span>
31   </body>
32 </html>

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020