Hour 11. Accessing Data Outside the Web Page


What You’ll Learn in This Hour:

Image Adding timers to web pages

Image Getting and setting cookies

Image Creating pop-ups


Dynamic web pages often require you to access and, in some cases, even manipulate things beyond the HTML elements. JavaScript provides a rich set of objects and functions that allow you to access information about the screen, browser window, history, and more.

The first part of this hour describes the screen, window, location, and history objects that provide JavaScript with an interface to access information beyond the web page. The second part covers utilizing those objects to implement cookies, pop-up windows, and timers.

Understanding the Screen Object

You have already seen the screen object in use in previous hours. You have used the screen object to get the color depth as well as the height and width of the screen. Getting the screen dimensions has become more important with the shift toward mobile devices and tablets.

A wide range of screen sizes is available; therefore, you must be able to design your web pages and dynamic interactions to take the screen size into account.

Table 11.1 describes the full set of properties available on the screen object.

Image

TABLE 11.1 Screen Object Properties

Using the Window Object

The window object is by far the most robust of the external object set. The window object provides access to the browser window, allowing you to get information such as the dimensions and position of the browser window.

Using the window object, you can also create and control new browser windows when you want to display additional web content but do not want to navigate away from the current page.

The following sections describe some of the methods and properties attached to the window object.

Accessing the Window Object Properties

The window object provides you with important information about browser windows. You can access the size and position of the current window or even its parent window. For example, the following code gets the pixels down and left from the top left of the screen to the top left of the browser:

var fromTop = window.self.screenY;
var fromLeft = window.self.screenX;

Table 11.2 shows a list of some of the more important window object properties and what they are used for.

Image

TABLE 11.2 Window Object Properties

Using the Window Object Methods

The window object also provides a set of methods that allow you to create and manage additional child windows from your JavaScript code.

For example, the following code opens a new browser window and loads the URL specified:

var tempWindow = window.open("http://jquery.com");

Later, from the JavaScript code in your original web page, you can close the new window using the following statement:

tempWindow.close();

Table 11.3 shows a list of some of the more important window object properties and what they are used for.

Image

TABLE 11.3 Window Object Methods

Using the Browser Location Object

The browser location object gives you access to the current location in the browser. This allows you to access all the URL information as well as reload the current page or load a new one in the current window.

For example, the following statement gets the following URL from the current page and then loads a new page at a different URL:

var oldURL = location.href;
location.assign("http://jquery.com");

Also, if the URL was linked to a specific anchor on the web page, you can get that portion of the URL using location.hash. You can use the anchor points that have existed in static web pages as a way to provide backward compatibility with other web pages that link to specific locations. You read the anchor hash and then adjust the dynamic content to match what was located at that portion of the original web page.

var anchor = location.hash;

Table 11.4 shows a list of the location object properties and methods.

Image

TABLE 11.4 Location Object Properties and Methods

Using the Browser History Object

The history object provides access to the browser navigation history, allowing you to move forward and backward dynamically without the user needing to click the browser Forward and Back buttons.

Navigating Forward in the Browser History

To move forward, you can use history.forward() to move to the next URL in the history, or you can use history.go(n), where n is a positive number that represents the number of steps to move forward. For example, the following statement moves three URLs forward:

history.go(3);

Navigating Backward in the Browser History

To move backward, you can use history.back() to move to the previous URL in the history, or you can use history.go(n), where n is a negative number that represents the number of steps to move backward. For example, the following statement moves two URLs back:

history.go(-2);

Controlling External Links

An important part of dynamic web programming also involves controlling the linkage outside of the web page. The following sections describe some of the ways that you can control the behavior of external links by preventing them from happening or forcing them to open new browser windows.

Stopping External Links on a Web Page

A useful task that you can perform with a simple jQuery script is stopping external links from happening. This allows you to lock linking away from the web page using one of the <a> elements within it.

To lock down external links from a web page, you need to first add a click event handler to the <a> tags that link externally and then call preventDefault() on the click event object. For example, the following code finds <a> tags where the href begins with http:// and then adds a click handler function that prevents the default browser action:

$('a[href^="http://"').click(function (e){
    any of your own handler code . . .
    e.preventDefault();
  });

Forcing Links to Open in New Browser Windows

Another useful task that you can perform with a simple jQuery script is forcing external links to open in new windows. This allows the current window to remain available.

To force external links to open in a new window, set the target attribute to "_blank" for <a> tags that link externally. For example, the following code finds <a> tags where the href begins with http:// and then sets the target attribute to "_blank", forcing the links to open in a new browser window when clicked:

$('a[href^="http://"').attr("target", "_blank");

Adding Pop-up Boxes

The window provides several methods that allow you to launch pop-up windows that you can interact with for alerts, prompts, and notifications. The pop-up windows are displayed, and the user needs to interact with the pop-up before continuing to access the web page.


Note

It is often much better to create a fixed position <div> element with an overlay rather than using these pop-up boxes because you have much more control over them. You learn how to do just that a little later in the book.


Notifying the User

The most common type of pop-up is an alert pop-up designed to notify the user that something has happened. The user will see the message; however, the only option given is to close the pop-up message.

To create a simple alert message, use the window.alert() method as shown next and displayed in Figure 11.2:

window.alert("It's 12/12/12 12:12:12!!!");

Image

FIGURE 11.2 JavaScript pop-up boxes.

Asking the User to Confirm

The next most common type of pop-up is a confirmation pop-up designed to notify the user that something is about to happen. The user will see the message and then be given the option to click OK to allow the action to occur or click Cancel to reject the action.

To create a confirmation dialog box that allows the user to respond with yes or no, use the window.confirm() method, as shown next and displayed in Figure 11.2:

var response = window.confirm("Are you sure?");
if (response == true) { do something; }
else { don't do something; }

Prompting the User for Input

Another type of pop-up is the prompt. The prompt displays a text box that allows the user to type a text string into the pop-up box. That string is returned to the JavaScript code and can be used in various ways.

To create a prompt dialog that allows the user to input a single text string as input, use the window.prompt() method, as shown next and displayed in Figure 11.2:

var response = window.prompt("What is the airspeed velocity of an unlaiden swallow?");
if (response == "African or European?"){ pass }
else { no pass }

Setting Timers

Another useful feature of JavaScript is the capability to set timers that execute a function or evaluate an expression after a certain amount of time or on a specific interval.

Using timers allows you to delay the execution of code so that it does not need to happen at the exact moment an event is triggered or the page is loaded.

Adding a Delay Timer

To delay the execution of code for a certain amount of time, use the setTimeout(code, ms) method, where code is either a statement or a function that will execute when the time expires. ms is the number of milliseconds. For example, to execute a function named myTimer() in 10 seconds, you would use the following:

var timerId = setTimeout(myTimer, 10000);

At any point before the time runs out and the code is executed, you can clear the timer by calling clearTimeout(id) method using the ID returned from setTimeout(). For example:

clearTimeout(timerId);

Adding a Reccurring Timer

You can also start a timer that will trigger on a regular interval using the setInterval(code, ms) method. This method also accepts a code statement or a function name and milliseconds as arguments. For example, the following code creates a timer that triggers every minute and calls a function checkStatus():

var timerId = setInterval(checkStatus, 60000);

You can also turn off an interval timer using the clearInterval() method, as shown next:

clearInterval(timerId);

Summary

This hour has focused on using JavaScript objects to access data outside the web page. You learned that there are screen, window, browser, location, and history objects that provide a myriad of details about the physical screen, browser, and client history, as well as access to cookies.

You saw how to open and close browser windows. Using JavaScript, you also learned how to create basic pop-ups that allow you to interact with the user.

Q&A

Q. Is there a way to find out what operating system and browser is being used?

A. Yes. The navigator object will show you the browser in the window.navigator.appCodeName attribute. You can also get the operating system using window.navigator.platform.

Workshop

The workshop consists of a set of questions and answers designed to solidify your understanding of the material covered in this hour. Try to answer the questions before looking at the answers.

Quiz

1. What are the three types of pop-up boxes supported by JavaScript?

2. How do you use JavaScript to find the full URL that was used to load the web page?

3. True or False: You can navigate backward through the browser history but not forward.

Quiz Answers

1. Alert, confirmation, and prompt.

2. Access the location.href attribute.

3. False. You can navigate forward using history.forward() or history.go(n).

Exercises

1. Open the code in Listing 11.1 and modify the ready() function to get a cookie named buttonColor. If the buttonColor cookie is set, change the color of the buttons using the following jQuery line:

$("span").css("color", getCookie("buttonColor"));

2. Open the code in Listing 11.2 and modify the prompt to ask the user for a number of seconds before the next notification. If the user enters 0, terminate the notification. Otherwise, use the value in the setTimeout() call. Remember that you need to multiply the number of seconds by 1000 to get milliseconds.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset