Interacting with the Browser - jQuery and JavaScript Phrasebook (2014)

jQuery and JavaScript Phrasebook (2014)

3. Interacting with the Browser

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 phrases in this chapter describe ways to use the screen, window, location, and history objects that provide JavaScript with an interface to access information beyond the web page. Additional phrases describe utilizing those objects to implement cookies, popup windows, and timers.

Writing to the JavaScript Console


console.log("This is Debug"); //"This is Debug" is displayed in console
var x=5;
console.log("x="+x): //"x=5" is displayed in console


The JavaScript console can be an important tool when debugging problems in your jQuery and JavaScript code. The console log is simply a location where you can view data output from the JavaScript code. Each of the major browsers has a console log tool that displays the output.

To output data to the console log, use console.write(DEBUG_STRING) and pass it the text that you want to display on the console.

Reloading the Web Page


location.reload()


A useful feature of JavaScript is the ability to force the browser to reload the current web page. You may want to reload the web page because data has changed on the server or a certain amount of time has elapsed. The location.reload() method requests that the browser reload the current URL.

Redirecting the Web Page


location.href="newpage.html";
location.href="http://jqueryin24/index.html;


Another extremely useful feature of JavaScript is the ability to redirect the browser away from the current URL to another location. You do this by setting the location.href value to a new URL. The new URL can be a full address, such as http://mysite.com/newlocation/index.html, or a relative location to the current URL, such as page2.html.

Getting the Screen Size


screen.availHeight; // returns screen height in pixels
screen.availWidth; // returns screen width in pixels


An important feature of JavaScript these days is the ability to get the screen size. The screen sizes of browsers vary so much that you often need to use different sets of code for larger, medium, or smaller screens. To get the screen size, use the screen.availHeight andscreen.availWidth attributes. These values are specified in the number of pixels.

Getting Current Location Details

The JavaScript location object provides an easy way to get various pieces of information about the URL the user is currently viewing. Because JavaScript and jQuery code are often used across multiple pages, the location object is the means to get information about what URL the browser is currently viewing. The following sections provide some phrases that provide information about the browser’s current location.

Finding the Current Hash


location.hash


The location.hash value returns the current hash, if any, that the browser is using. This is useful when you are displaying a web page with multiple hash anchors. The hash provides a context to the location on the page the user actually clicked.

Getting the Host Name


location.hostname


The location.hostname value returns the domain name of the server that sent the page to the user. This is just the portion after the protocol but before the port number or path. This allows you to determine which server to send AJAX requests back to. Often, multiple servers may handle the web site, but you may want to interact only with the server that served the web page in the first place.

Looking at the File Path


location.pathname


The location.pathname returns the path that the page was loaded from on the server. The pathname also provides a context as to what page the user is looking at.

Getting the Query String


location.search


The location.search value returns the query string that was passed to the server to load the page. Typically, you think about a query string as a server-side script tool. However, it can be just as valuable to JavaScript code that manipulates the data returned from the server and requests additional information from the server via AJAX.

Determining If the Page Is Viewed on a Secure Protocol


location.protocol


The easiest way to determine if a page is being viewed from a secured location on the server is to look at the location.protocol value. This value will be http on regular requests or https on secure requests.

Accessing the Browser

Another important object built into JavaScript is the window object. The window object represents the browser and provides you with a wealth of information about the browser position, size, and much more. It also allows you to open new child windows, close windows, and even resize the window.

Getting the Max Viewable Web Page Size


window.innerHeight; // returns browser view port height in pixels
window.innerWidth; // returns browser view port width in pixels


The window object provides the innerHeight and innerWidth of the browser window. These values represent the actual pixels in the browser window that the web page will be displayed within. This is a critical piece of information if you need to adjust the size and location of elements on the web page based on the actual area that is being displayed.

Setting the Text Displayed in the Browser Status Bar


window.status = "Requesting Data From Server . . .";


The browser has a status bar at the bottom. You can set the text that is displayed there to provide to the user additional information that does not belong on the page, such as the server name, current status of requests, and more. To set the text displayed in the browser status bar, set thewindow.status value equal to the string you want displayed.

Getting the Current Location in the Web Page


window.pageXOffset;
// number of pixels the page has scrolled to the right
window.pageYOffset;
// returns number of pixels the page has scrolled down


When writing dynamic code, it is often necessary to determine the exact location in the web page that is currently being viewed. When the user scrolls down or to the right, the position of the page to the frame of the browser view port changes.

To determine the number of pixels the page has scrolled to the right, use the window.pageXOffset attribute. To determine the number of pixels the page has scrolled down, use the window.pageYOffset attribute.

Opening and Closing Windows


//Opens a new blank window, writes to it, and then closes it.
var newWindow = window.open();
newWindow.document.write("Hello From a New Window");
newWindow.close();
//Opens another URL in a new window
window.open("http://google.com");


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 window.open(URL) method opens a new window and returns a new window object. If you do not specify a URL, the browser opens a blank page that can be written to using the window.document object.

You can call .close() on window objects that you have created, and they will be closed.

Using the Browser History to Go Forward and Backward Pages


history.forward(); //forward 1 page
history.back(); //backward 1 page
history.go(-2); //backward 2 pages


The browser keeps track of the pages that have been navigated to in a history. JavaScript allows you to access this history to go forward or backward pages. This allows you to provide forward and backward controls to your web pages. You can also use this feature to provide bread crumbs displaying links to multiple pages back in the history.

To go forward one page, use history.forward(). To go backward one page, use history.back().

To go forward or backward multiple pages, use history.go(n), where n is the number of pages. A negative number goes backward that many pages, and a positive number goes forward that many pages.

Creating Popup Windows


var result = confirm("You Entered " + response +
"is that OK?");
if(result){ alert("You Said Yes.") }
else {alert("You Said no.")}


Window objects provides several different methods that allow you to launch popup windows that you can interact with for alerts, prompts, and notifications. The popup windows are displayed, and the user needs to interact with the popup before continuing to access the web page.

There are three kinds of popup boxes that can be created:

Image alert(msg)—Launches a popup window that displays an alert message and provides a button to close the popup.

Image confirm(msg)—Launches a popup window that displays a confirmation and message provides an OK and a Cancel button, which both close the popup. If you click the OK button, the return value from confirm() is true; otherwise, it is false.

Image prompt(msg)—Launches a popup window that displays the message, a text box for input, and an OK and Cancel button, which both close the popup. If you click the OK button, the return value from prompt() is the text typed into the text box; otherwise, it is false.

The code that follows illustrates these popup boxes, as shown in Figure 3.1.


01 <html>
02 <head>
03 <title>Python Phrasebook</title>
04 <meta charset="utf-8" />
05 <script type="text/javascript"
06 src="../js/jquery-2.0.3.min.js"></script>
07 <script>
08 var response = prompt("What is the airspeed " +
09 "velocity of an unladen swallow:");
10 var result = confirm("You Entered " + response +
11 "is that OK?");
12 if(result){ alert("You may pass.") }
13 else {alert("None Shall Pass.")}
14 </script>
15 </head>
16 <body>
17 </body>
18 </html>


ch0301.html

Image

Figure 3.1 Various popup boxes, with the results being passed from popup to popup using JavaScript.


By the way

It is often much better to create a fixed position <div> element with an overlay than to use these popup boxes because you have much more control over them. I’ll show you how to do just that a little later in the book.


Manipulating Cookies

A common task in JavaScript is getting and setting cookies in the browser. Cookies allow you to store simple key value pairs of information in the browser in a persistent manner. You can access the cookies by the server-side scripts and JavaScript to determine what those values are.

You can access cookie information using the document.cookie object. This object contains all the cookies in the string format name=value; name=value; ....

Setting a Cookie Value in the Browser


function setCookie(name, value, days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = name + "=" + value +
expires + "; path=/";
}


To add a new cookie for your web site, set document.cookie = "name=value; expireDate; path;";. The expire date needs to be a date set using .toGMTString(), and the path is the path on your web site that the cookie applies to.

Getting a Cookie Value from the Browser


function getCookie(name) {
var cArr = document.cookie.split(';');
for(var i=0;i < cArr.length;i++) {
var cookie = cArr[i].split("=",2);
cookie[0] = cookie[0].replace(/^\s+/,"");
if (cookie[0] == name){ return cookie; }
}
}


To get the value of the cookie, split the document.cookie value using the ; character, and then iterate through the resulting array until you find the name you are looking for.

Example Getting and Setting Cookies

The following code shows a full example of setting and getting cookies. When the code is run, two cookies are set: one for name and the other for language. The cookies are then retrieved from the browser and written to the web page, as shown in Figure 3.2.


01 <html>
02 <head>
03 <title>Python Phrasebook</title>
04 <meta charset="utf-8" />
05 <script type="text/javascript"
06 src="../js/jquery-2.0.3.min.js"></script>
07 <script>
08 function setCookie(name, value, days) {
09 var date = new Date();
10 date.setTime(date.getTime()+(days*24*60*60*1000));
11 var expires = "; expires="+date.toGMTString ();
12 document.cookie = name + "=" + value +
13 expires + "; path=/";
14 }
15 function getCookie(name) {
16 var cArr = document.cookie.split(';');
17 for(var i=0;i < cArr.length;i++) {
18 var cookie = cArr[i].split("=",2);
19 cookie[0] = cookie[0].replace(/^\s+/,"");
20 if (cookie[0] == name){ return cookie; }
21 }
22 }
23 setCookie("name", "Brad", 1);
24 setCookie("language", "English", 1);
25 document.write("<h3>Cookies</h3>");
26 var c1 = getCookie("name");
27 document.write(c1[0] + " is set to "+ c1[1] +"<br>");
28 var c2 = getCookie("language");
29 document.write(c2[0] + " is set to " + c2[1]);
30 </script>
31 </head>
32 <body>
33 </body>
34 </html>


ch0302.html

Image

Figure 3.2 Adding cookie output using JavaScript.

Adding Timers

Another useful feature of JavaScript is the ability 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. The following phrases show you how to create timers to delay code execution and to apply recurring actions.

Adding a Delay Timer


function myTimer () {
alert("Timer Function Executed");
}
var timerId = setTimeout(myTimer, 10000);


To simply 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 executes 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:

setTimeout(myTimer, 10000);

Cancel a Timer


function myTimer () {
alert("Timer Function Executed");
}
var timerId = setTimeout(myTimer, 10000);
clearTimeout(timerId); //timer will not execute


At any point before the time runs out and the code is executed, you can clear the timer by calling the clearTimeout(id) method using the ID returned from setTimeout(). Once the timer has been cleared, it does not execute. You need to keep track of the ID returned fromsetTimeout() using a variable.

Adding a Recurring Timer


var statusTimerId;
var status = "OK";
//checks status every minute as long as it is "OK"
function checkStatus () {
if(status == "OK"){
alert("Status OK");
statusTimerId = setInterval(checkStatus, 60000);
} else {
alert("Status Failed");
}
}
statusTimerId = setInterval(checkStatus, 60000);


You can also start a timer that triggers on a regular interval using the setInterval(function, ms) method. This method also accepts a function name and milliseconds as arguments. Inside the function, you need to call set interval again on the same function so that the code will be called again.

To turn off the recurring timer, simply do not call setInterval() again inside the timer function, or use clearInterval() outside the function.