Archive for the 'MySQL' Category

Net web server - BC452Part VIBonus Chapters} else if (evt.offsetX || evt.offsetY)

Sunday, January 20th, 2008

BC452Part VIBonus Chapters} else if (evt.offsetX || evt.offsetY) { offsetX = evt.offsetX - ((evt.offsetX < -2) ? 0 : document.body.scrollLeft); offsetY = evt.offsetY - ((evt.offsetY < -2) ? 0 : document.body.scrollTop); } setBGColor(selectedStateLabel, yellow ); return false; } } The dragIt()function, compact as it is, provides the main action in the application by keep- ing a selected state object under the cursor as the user moves the mouse. This function iscalled repeatedly by the mousemoveevents, although the actual event handling methodol- ogy varies with platform (precisely the same way as with engage(), as shown previously). Regardless of the event property detected, event coordinates (minus the previously pre- served offsets) are passed the shiftTo()function in the API. Before the dragging action branch of the function ends, the event object s cancelBubbleproperty is set to true. In truth, only the IE4+ and W3C DOM event objects have such a prop- erty, but assigning a value to a nonexistent object property for NN4 does no harm. It s impor- tant that this function operate as quickly as possible, because it must execute with eachmousemoveevent. Canceling event bubbling helps in a way, but more important, the cancella- tion allows the mousemoveevent to be used for other purposes, as described in a moment. // move div on mousemovefunction dragIt(evt) { evt = (evt) ? evt : event; if (selectedObj) { if (evt.pageX) { shiftTo(selectedObj, (evt.pageX - offsetX), (evt.pageY offsetY)); } else if (evt.clientX || evt.clientY) { shiftTo(selectedObj, (evt.clientX - offsetX), (evt.clientY offsetY)); } evt.cancelBubble = true; return false; } } When a user drops the currently selected map object, the release()function invokes theonTarget()function to find out if the current location of the map is within range of thedesired destination. If it is in range, the background color of the state label object is set togreen, and the done property of the selected state s database entry is set to true. One addi- tional test (the isDone()function call) looks to see if all the done properties are truein thedatabase. If so, the congratsobject is shown. But if the object is not in the right place, thelabel reverts to its original red color. In case the user moves a state that was previously okay, its database entry is also adjusted. No matter what the outcome, however, the user hasdropped the map, so key global variables are set to nulland the layer order for the item isset to zero (bottom of the heap) so that it doesn t interfere with the next selected map. One more condition is possible in the release()function. As shown later in the initializationfunction, the documentobject s onmousemoveevent handler is assigned to the release() function (to compare the onmousemoveevents for the state maps go to dragIt()). The rea- soning behind this document-level event assignment is that no matter how streamlined thedragging function may be, it is possible for the user to move the mouse so fast that the mapcan t keep up. At that point, mousemoveevents are firing at the document(or other object,

BC451Chapter 56Application: Cross-Browser DHTML Map Puzzle} else if (Best web hosting site)

Saturday, January 19th, 2008

BC451Chapter 56Application: Cross-Browser DHTML Map Puzzle} else if (document.all) { selectedObj = document.all(abbrev + map ); selectedStateLabel = document.all(abbrev + label ); } else if (document.getElementById) { selectedObj = document.getElementById(abbrev + map ); selectedStateLabel = document.getElementById(abbrev + label ); } setZIndex(selectedObj, 100); return; } selectedObj = null; selectedStateLabel = null; return; } Next comes the engage()function definition. This function is invoked by mousedowneventsinside any of the state map layers (event handler assignment code comes later). NN4+/W3CDOM browsers pass an event object as the sole parameter to the function (picked up by theevtparameter variable). If that parameter contains a value, it stands as the event object forthe rest of the processing; but for IE, the window.eventobject is assigned to the evtvariable. After setting the necessary object globals through setSelectedMap(), the next major taskfor engage()is to calculate and preserve in global variables the number of pixels within thestate map layer at which the mousedownevent occurred. By preserving these values, thedragIt()function makes sure that the motion of the state map layer keeps in sync with themouse cursor at the very same point within the state map. If it weren t for taking the offsetinto account, the layer would jump unexpectedly to bring the top-left corner of the layerunderneath the cursor. That s not how users expect to drag items on the screen. The calculations for the offsets require a variety of DOM-specific properties. For example, both NN4 and NN6+ offer pageXand pageYproperties of the eventobject, but the coordi- nates of the layer itself require left/topproperties for NN4 and offsetLeft/offsetTopproperties for NN6+. A nested object detection takes place in each assignment statement. TheIE branch has some additional branching within each of the assignment statements. These extra branches cover a disparity in the way WinIE and MacIE report the offset proper- ties of an event. WinIE ignores window scrolling, while MacIE takes scrolling into account. Later calculations for positioning must take window scrolling into account, so that scrollingisfactored into the preserved offset global values if there are indications that the windowhasscrolled and the values are being affected by the scroll (in which case the offset valuesgovery negative). The logic is confusing, and it won t make much sense until you see laterhow the positioning is invoked. Conceptually, all of these offset value calculations may seemlike a can of worms, but they are essential, and are performed amazingly compactly. After the offsets are established, the state s label layer s background color is set to yellow. The function ends with return falseto make sure that the mousedownevent doesn t propa- gate through the page (causing a contextual menu to appear on the Macintosh, for instance). // set relevant globals onmousedown; set selected map// object global; preserve offset of click within// the map coordinates; set label color to yellowfunction engage(evt) { evt = (evt) ? evt : event; setSelectedMap(evt); if (selectedObj) { if (evt.pageX) { offsetX = evt.pageX - ((selectedObj.offsetLeft) ? selectedObj.offsetLeft : selectedObj.left); offsetY = evt.pageY - ((selectedObj.offsetTop) ? selectedObj.offsetTop : selectedObj.top);

Free web hosting with ftp - BC451Chapter 56Application: Cross-Browser DHTML Map Puzzle} else if

Saturday, January 19th, 2008

BC451Chapter 56Application: Cross-Browser DHTML Map Puzzle} else if (document.all) { selectedObj = document.all(abbrev + map ); selectedStateLabel = document.all(abbrev + label ); } else if (document.getElementById) { selectedObj = document.getElementById(abbrev + map ); selectedStateLabel = document.getElementById(abbrev + label ); } setZIndex(selectedObj, 100); return; } selectedObj = null; selectedStateLabel = null; return; } Next comes the engage()function definition. This function is invoked by mousedowneventsinside any of the state map layers (event handler assignment code comes later). NN4+/W3CDOM browsers pass an event object as the sole parameter to the function (picked up by theevtparameter variable). If that parameter contains a value, it stands as the event object forthe rest of the processing; but for IE, the window.eventobject is assigned to the evtvariable. After setting the necessary object globals through setSelectedMap(), the next major taskfor engage()is to calculate and preserve in global variables the number of pixels within thestate map layer at which the mousedownevent occurred. By preserving these values, thedragIt()function makes sure that the motion of the state map layer keeps in sync with themouse cursor at the very same point within the state map. If it weren t for taking the offsetinto account, the layer would jump unexpectedly to bring the top-left corner of the layerunderneath the cursor. That s not how users expect to drag items on the screen. The calculations for the offsets require a variety of DOM-specific properties. For example, both NN4 and NN6+ offer pageXand pageYproperties of the eventobject, but the coordi- nates of the layer itself require left/topproperties for NN4 and offsetLeft/offsetTopproperties for NN6+. A nested object detection takes place in each assignment statement. TheIE branch has some additional branching within each of the assignment statements. These extra branches cover a disparity in the way WinIE and MacIE report the offset proper- ties of an event. WinIE ignores window scrolling, while MacIE takes scrolling into account. Later calculations for positioning must take window scrolling into account, so that scrollingisfactored into the preserved offset global values if there are indications that the windowhasscrolled and the values are being affected by the scroll (in which case the offset valuesgovery negative). The logic is confusing, and it won t make much sense until you see laterhow the positioning is invoked. Conceptually, all of these offset value calculations may seemlike a can of worms, but they are essential, and are performed amazingly compactly. After the offsets are established, the state s label layer s background color is set to yellow. The function ends with return falseto make sure that the mousedownevent doesn t propa- gate through the page (causing a contextual menu to appear on the Macintosh, for instance). // set relevant globals onmousedown; set selected map// object global; preserve offset of click within// the map coordinates; set label color to yellowfunction engage(evt) { evt = (evt) ? evt : event; setSelectedMap(evt); if (selectedObj) { if (evt.pageX) { offsetX = evt.pageX - ((selectedObj.offsetLeft) ? selectedObj.offsetLeft : selectedObj.left); offsetY = evt.pageY - ((selectedObj.offsetTop) ? selectedObj.offsetTop : selectedObj.top);

BC450Part VIBonus Chapterslist (Free php web host) of abbreviations as its own

Saturday, January 19th, 2008

BC450Part VIBonus Chapterslist of abbreviations as its own array. This becomes necessary later on when the script needsto loop through all objects in the statesarray to check their doneproperties. Because thearray is set up like a hash table (with string index values), a forloop using numeric indexvalues is out of the question. So, this extra statesIndexListarray provides a numericallyindexed array that can be used in a forloop; values of that array can then be used as indexvalues of the statesarray. Yes, it s a bit of indirection, but other parts of the application ben- efit greatly by having the state information stored in a hash-table-like array. We now come to the functions that operate while the user interacts with the map puzzlepieces. The first function, acting as a vital behind-the-scenes utility function, is calledsetSelectedMap(). It receives as its sole parameter an event object that is of the propertype for the browser currently running (that s done in the engage()function, describednext). This function has three jobs to do, two of which set global variables. The first globalvariable, selectedObj, maintains a reference to the layer (puzzle piece) being dragged bythe user. At the same time, the selectedStateLabelvariable holds onto a reference to thelayer that holds the label (recall that its color changes during dragging and release). All ofthis requires DOM-specific references that are generated through the aid of object detectingbranches of the function. The last job of this function is to set the stacking order of the selectedmap to a value higher than the others so that while the user drags the map, it is in front ofeverything else on the page. To assist in establishing references to the map and label layers, naming conventions of theHTML objects (shown later in the code) play an important role. Despite the event handlersbeing assigned to the divs that hold the images, the mouse events are actually targeted atthe image objects. The code must associate some piece of information about the event targetwith the divthat holds it ( parent types of references don t work across all browsers, so wehave to make the association the hard way). To prevent conflicts with so many objects onthis page named with the lowercase abbreviations of the states, the image objects are assigneduppercase abbreviations of the state names. As setSelectedMap()begins to execute, it usesobject detection to extract a reference to the element object regarded as the target of theevent (targetin W3C DOM browsers, srcElementin IE). To make sure that the event beingprocessed comes from an image, the next statement makes sure that the target has both nameand srcproperties, in which case a lowercase version of the name is assigned to the abbrevlocal variable (if only IE4+ and W3C DOMs were in play here, a better verification is checkingthat the tagNameproperty of the event target is img). That abbrevvariable then becomesthebasis for element names used in references to objects assigned to selectedObjandselectedStateLabel. Notice how the NN4 version requires a double-layer nesting to thereference for the label because labels are nested inside the bgmaplayer. The presence of a value assigned to selectedObjbecomes an important case for all threedrag-related functions later. That s why the setSelectedMap()function nulls out the valueifthe event comes from some other source. /************************************************* BEGIN INTERACTION FUNCTIONS**************************************************/ // set global reference to map being engaged and draggedfunction setSelectedMap(evt) { var target = (evt.target) ? evt.target : evt.srcElement; var abbrev = (target.name && target.src) ? target.name.toLowerCase() : ; if (abbrev) { if (document.layers) { selectedObj = document.layers[abbrev + map ]; selectedStateLabel = document.layers[ bgmap ].document.layers[abbrev + label ];

Unlimited web hosting - BC449Chapter 56Application: Cross-Browser DHTML Map PuzzleNow comes the

Friday, January 18th, 2008

BC449Chapter 56Application: Cross-Browser DHTML Map PuzzleNow comes the main script, which contains all the document-specific functions and globalvariables. Global variables here are ready to hold information about the selected state object(and associated details), as well as the offset between the position of a click inside a mapobject and the top-left corner of that map object. You will see that this offset is important toallow the map to track the cursor at the same offset position within the map. And becausethe tracking is done by repeated calls to a function (triggered by numerous mouse events), these offset values must have global scope. // global declarationsvar offsetX = 0; var offsetY = 0; var selectedObj; var states = new Array(); var statesIndexList = new Array(); var selectedStateLabel; As you will see later in the code, an onloadevent handler for the document invokes an initial- ization function, whose main job is to build the array of objects containing information abouteach state. The fields for each stateobject record are for the two-letter state abbreviation, the full name (not used in this application, but included for use in a future version), the x andy coordinates (within the coordinate system of the background map) for the exact position ofthe state, and a Boolean flag to be set to truewhenever a user correctly places a state. Icome back to the last two statements of the constructor function in a moment. Calculating the data for the x and y coordinates required some legwork during development. As soon as I had the pieces of art for each state and the code for dragging them around thescreen, I disengaged the part of the script that tested for accuracy. Instead, I added a state- ment to the code that revealed the x and y position of the dragged item in the status bar (ratherthan being bothered by alerts). When I carefully positioned a state in its destination, I copiedthe coordinates from the status bar into the statement that created that state record. Sure, itwas tedious, but after I had that info in the database, I could adjust the location of the back- ground map and not have to worry about the destination coordinates, because they werebased on the coordinate system inside the background map. // object constructor for each state; preserves destination// position; invokes assignEvents() function state(abbrev, fullName, x, y) { this.abbrev = abbrev; this.fullName = fullName; this.x = x; this.y = y; this.done = false; assignEvents(this); statesIndexList[statesIndexList.length] = abbrev; } // initialize array of state objectsfunction initArray() { states[ ca ] = new state( ca , California , 7, 54); states[ or ] = new state( or , Oregon , 7, 24); states[ wa ] = new state( wa , Washington , 23, 8) ; states[ id ] = new state( id , Idaho , 48, 17); states[ az ] = new state( az , Arizona , 45, 105); states[ nv ] = new state( nv , Nevada , 27, 61); states[ ut ] = new state( ut , Utah , 55, 69); } The act of creating each stateobject causes all statements in the constructor function toexecute. Moreover, they were executing within the context of the object being created. Thatopened up channels for two important processes in this application. One was to maintain a

Web hosting domains - BC448Part VIBonus ChaptersListing 56-1: The Main Program (mapgame.htm)

Thursday, January 17th, 2008

BC448Part VIBonus ChaptersListing 56-1: The Main Program (mapgame.htm) Most of the positionable elements have their CSS properties established in the The next statement loads the external .jslibrary file that contains the API described inChapter 47. I tend to load external library files before listing any other JavaScript codeinthepage, just in case the main page code relies on global variables or functions in itsinitializations.

Web hosting ratings - BC447Chapter 56Application: Cross-Browser DHTML Map Puzzlelook better. And,

Thursday, January 17th, 2008

BC447Chapter 56Application: Cross-Browser DHTML Map Puzzlelook better. And, while the code could use scripts to generate layers for NN4 and divs forothers, the choice here was to stay with divelements alone. If you try this game on NN4 andother DHTML browsers, you will see minor differences in the way the labels are colored (red, yellow, and green) during game play. All other rendering and behavior is identical (although arendering bug in NN6 is discussed later). Implementation DetailsDue to the number of different scripted properties being changed in this application, I decidedto implement a lot of the cross-platform scripting as a custom API loaded from an external .jsfile library. The library, whose code is dissected and explained in Chapter 47, contains func- tions for most of the scriptable items you can access in DHTML. Having these functions avail- able simplified what would have been more complex functions in the main part of theapplication. Although I frown on using global variables except where absolutely necessary, I needed toassign a few globals for this application. All of them store information about the state mapcurrently picked up by the user and the associated label. This information needs to survivethe invocations of many functions between the time the state is picked up until it is droppedand checked against the database of state data. That database is another global object a global that I don t mind using at all. Constructedas a multidimensional array, each record in the database stores several fields about thestate, including its destination coordinates inside the outline map and a Boolean field to storewhether the state has been correctly placed in position. Out of necessity for NN4, the state map images are encased in individual divelements. Thismakes their positionable characteristics more stable, as well as making it possible to capturemouse events that NN4 s image objects do not recognize. If the application were being doneonly for IE4+ and W3C DOMs, the images themselves could be positionable, and the DHTMLAPI could be used without modification. You could certainly argue that it s time to let go ofversion 4 browsers and move forward, but to maximize compatibility across the broadestpossible user base, supporting version 4 browsers whenever possible still isn t a bad idea. The custom APITo begin the analysis of the code, you should be familiar with the API that is linked in from anexternal .js library file. Listing 47-2 contains that code and its description. The main programCode for the main program is shown in Listing 56-1. The listing is a long document, so I inter- lace commentary throughout the listing. Before diving into the code, however, allow me topresent a preview of the structure of the document. With two exceptions (the map silhouetteand the help panel), all positionable elements have their styles set via stylesheets in the headof the document. Notice the way class and id selectors are used to minimize the repetitivenature of the styles across so many similar items. After the stylesheets come the scripts forthe page. All of this material is inside the tag section. I leave the section tocontain the visible content of the page. This approach is an organization style that works wellfor me, but you can adopt any style you like, provided various elements that support otherson the page are loaded before the dependent items (for example, define a style before assign- ing its name to the corresponding content tag s ID attributes).

BC446Part VIBonus ChaptersFigure 56-1:The puzzle map game DHTML (Multiple domain web hosting)

Wednesday, January 16th, 2008

BC446Part VIBonus ChaptersFigure 56-1:The puzzle map game DHTML example. (Images courtesy Map Resources www.mapresources.com) When the page initially loads, all the state maps are presented across the top of the puzzlearea. The state labels all have a red background, and the silhouette of the continental UnitedStates has no features in it. To the right of the title is a question mark icon. A click of this iconcauses a panel of instructions to glide to the center of the screen from the right edge of thebrowser window. That panel has a button that hides the panel. To play the game (no scoring or time keeping is in this simplified version), a user clicks anddrags a state with the goal of moving it into its rightful position on the silhouette. While theuser drags the state, its label background to the right of the main map turns yellow to high- light the name of the state being worked on. To release the state in its trial position, the userreleases the mouse button. If the state is within a 4-pixel square region around its true loca- tion, the state snaps into its correct position and the corresponding label background colorturns green. If the state is not dropped close enough to its destination, the label backgroundreverts to red, meaning that the state still needs to be placed. After the last state map is dropped into its proper place, all the label backgrounds will begreen, and a congratulatory message is displayed where the state map pieces originally lay. Should a user then pick up a state and drop it out of position, the congratulatory messagedisappears. I had hoped that all versions of the application would look the same on all platforms. Theydo, with one small exception. Because the labels are generated as positioned divelementsfor all browsers, NN4 (especially on the Windows version) doesn t do as good a rendering jobas other browsers. If I were to use genuine layerelements for the labels just for NN4, they d

Business web hosting - Application: Cross-BrowserDHTML Map PuzzleDynamic HTML allows scripts to

Tuesday, January 15th, 2008

Application: Cross-BrowserDHTML Map PuzzleDynamic HTML allows scripts to position, overlap, and hide orshow elements under the control of stylesheets and scripting. To demonstrate modern cross-browser DHTML development tech- niques, this chapter describes the details of a jigsaw puzzle gameusing pieces of a map of the lower 48 United States (I think every- one would guess where Alaska and Hawaii go on a larger map ofNorth America). I chose this application because it allows me todemonstrate several typical tasks you might want to script in DHTML: hiding and showing elements; handling events for multiple elements; tracking the position of an element with the mouse cursor; absolutepositioning of elements; changing the z-order of elements; changingelement colors; and animating movement of elements. As with virtually any programming task, the example code here is notlaid out as the quintessential way to accomplish a particular task. Each author brings his or her own scripting style, experience, andimplementation ideas to a design. Very often, you have available sev- eral ways to accomplish the same end. If you find other strategies ortactics for the operations performed in these examples, it means youare gaining a good grasp of both JavaScript and Dynamic HTML. The Puzzle DesignFigure 56-1 shows the finished map puzzle with the game in progress. To keep the code to a reasonable length, the example provides posi- tionable state maps for only seven western states. Also, the overalldesign is intentionally Spartan so as to place more emphasis on thepositionable elements and their scripting, rather than on fancy design. 5656CHAPTER …In This ChapterApplying a DHTML dragging, and layering of multipleelementsEvent handling for threeDOMs at once …

BC444Part VIBonus ChaptersThe links at the bottom of (Web design portfolio)

Monday, January 14th, 2008

BC444Part VIBonus ChaptersThe links at the bottom of the document (see Figure 55-6) are coded to trigger JavaScript func- tions (rather than navigate to URLs) and include onmouseoverevent handlers to provide moreinformation about the link in the status bar: Review This Decision || Start a New Decision… Further ThoughtsIf you ve managed to follow through with this application s discussions, you will agree that it squite a JavaScript workout. But this application proves that, without a ton of code, JavaScriptprovides enough functionality to add a great deal of interactivity and pseudo-intelligence toan otherwise flat HTML document. As an alternative to using cookies for data storage, I have also implemented a version of theapplication that uses text boxes defined in a frame defined with a row height of 0. This tech- nique further challenges the synchronization of frames during reloading when a user resizesthe browser window or navigates with the Back or Forward browser buttons. This alternateversion is located on the CD-ROM for your own investigation and comparison. Dynamic HTML also offers some possibilities for this application. The entire program can bepresented in a no-frame window, with the navigation, interactive content, and instructionsframes incorporated into individual positionable objects. The interactive content area can betreated almost like a slide show, with successive pages flying in from one edge. Not only is this application instructive for many JavaScript techniques, but it is also fun toplay with as a user. Some financial Web sites have adapted it to assist visitors with investmentdecisions. You can use it to dream about where to go on a dream vacation, or help you decidethe most ethical of a few paths confronting you in a personal dilemma. There s somethingabout putting in data, turning a crank, and watching results (with a bar chart to boot!) magi- cally appear on the screen. …