|
Sebelum masuk ke materi Ajax, terlebih dulu harus kita pelajari tentang javascript dan XML. Berikut adalah materi tentang JavaScript yang dicuplik2 dari ebook dan artikel2 di internet.
JavaScript What JavaScript Is Used For JavaScript programs are used to detect and react to user-initiated events, such as a mouse going over a link or graphic. They can improve a Web site with navigational aids, scrolling messages and rollovers, dialog boxes, dynamic images, shopping carts, and so forth. JavaScript lets you control the appearance of the page as the document is being parsed. Without any network transmission, it lets you validate what the user has entered into a form before submitting the form to the server. It can test to see if the user has plug-ins and send them to another site to get the plug-ins if needed. It has string functions and supports regular expressions to check for valid e-mail addresses, social security numbers, credit card data, and the like. JavaScript serves as a programming language. Its core language describes such basic constructs as variables and data types, control loops, if/else statements, switch statements, functions, and objects.[3] It is used for arithmetic calculations, manipulates the date and time, and works with arrays, strings, and objects. JavaScript also reads and writes cookie values, and dynamically creates HTML based on the cookie value. Javascript Event Handlers: | Event Handler | What It Affects | When It Happens | | onAbort | Images | When image loading has been interrupted. | | onBlur | Windows, frames, all form objects | When focus moves out of this object except hidden; e.g., when the cursor leaves a text box. | | onChange | Input, select, and text areas | When a user changes the value of an element and it loses the input focus. Used for form validation. | | onClick | Links, buttons, form objects, image map areas | When a user clicks on an object. Return false to cancel default action. | | onDblClick | Links, buttons, form objects | When a user double-clicks on an object. | | onDragDrop | Windows | When a user drops an object, such as a file, onto the browser window. | | onError | Script | When an error in the script occurs; e.g., a syntax error. | | onFocus | Windows, frames, all form objects | When a mouse is clicked or moved in a window or frame and it gets focus; except hidden. | | onKeyDown | Documents, images, links, forms | When a key is pressed. | | onKeyPress | Documents, images, links, forms | When a key is pressed and released. | | onKeyUp | Documents, images, links, forms | When a key is released. | | onLoad | Body, framesets, images | After the document or image is loaded. | | onMouseOut | Links (and images within links) | When the mouse moves away from a link. | | onMouseOver | Links (and images within links) | When the mouse moves over a link. Return true to prevent link from showing in the status bar. | | onMove | Windows | When the browser window is moved. | | onReset | Forms reset button | When the forms reset button is clicked. Return false to stop reset. | | onResize | Windows | When the browser window changes size. | | onSelect | Form elements | When a form element is selected. | | onSubmit | Forms | When you want to send a form to the server. Return false to stop submission to the server. | | onUnload | Body, framesets | After the document or frameset is closed or reset. | Example : onClick <html> <head><title>Event</title></head> <body> <form> <input type ="button" value = "Pinch me" onClick="alert('OUCH!!')" > </form> </body> </html> Client-side JavaScript programs are embedded in an HTML document between HTML head tags <head> and </head> or between the body tags <body> and </body>. Example : embedding javascript <html> <head><title>First JavaScript Sample</title></head> <body bgcolor="yellow" text="blue"> <script language = "JavaScript" type="text/javascript"> document.writeln("<h2>Welcome to the JavaScript World!</h1>"); </script> <font size="+2">This is just plain old HTML stuff.</font> </body> </html> Interacting with the User Programs like to talk, ask questions, get answers, and respond. In the previous chapter, we saw how the write() and writeln() methods are used to send output to the browser. A method is how you do something, and JavaScript methods are the action words, the "doers" of the JavaScript language. They make things happen. JavaScript uses dialog boxes to interact with the user. The dialog boxes are created with three methods: · alert() · prompt() · confirm() Example : prompt var name=prompt("What is your name?", ""); document.write("<br>Welcome to my world! " + name + ".</font><br>"); var age=prompt("Tell me your age.", "Age"); if ( age == null){ // If user presses the cancel button alert("Not sharing your age with me"); } else{ alert(age + " is young"); } Example : confirm document.clear // Clears the page if(confirm("Are you really OK?") == true){ alert("Then we can proceed!"); } else{ alert("We'll try when you feel better? "); } Number, String, or Boolean? Datatype Conversion As defined earlier, JavaScript is a loosely typed language, which really means that you don't have to be concerned about what kind of data is stored in a variable. You can assign a number to x on one line and on the next line assign a string to x, you can compare numbers and strings, strings and Booleans, and so on. JavaScript automatically converts values when it assigns values to a variable or evaluates an expression. If data types are mixed (i.e., a number is compared with a string, a Boolean is compared with a number, a string is compared with a Boolean), JavaScript must decide how to handle the expression. Most of the time, letting JavaScript handle the data works fine, but there are times when you want to force a conversion of one type to another. For example, if you prompt a user for input, the input is set as a string. But, suppose you want to perform calculations on the incoming data, making it necessary to convert the strings to numbers. When using the + operator you want to add two numbers that have been entered as strings, not concatenate them, so you will then need to convert the data from string to number. JavaScript provides three methods to convert the primitive data types. They are: · String() · Number() · Boolean() <html> <head><title>The Conversion Methods</title></head> <body> <p> <h3>Data Conversion</h3> script language="JavaScript"> var num1 = prompt("Enter a number: ",""); var num2 = prompt("Enter another number: ",""); var result = Number(num1) + Number(num2); // Convert strings to numbers alert("Result is "+ result); var myString=String(num1); result=myString + 200; // String + Number is String alert("Result is "+ result); // Concatenates 200 to the // result; displays 20200 alert("Boolean result is "+ Boolean(num2)); // Prints true </script> </body> </html> The parseInt() Method This method converts a string to a number. It starts parsing at the beginning of the string and returns all integers until it reaches a non-integer and then stops parsing. If the string doesn't begin with an integer, NaN[2] (not a number) is returned. For example, parseInt("150cats") becomes 150, whereas parseInt("cats") becomes NaN. You can also use octal and hexadecimal numbers. In the two-argument format, the first argument to parseInt() is a string containing a number base (radix) ranging from 2 to 36. The default is base 10. In the statement, parseInt("17", 8), the result is 15. The first argument is the string to be parsed and the second argument, 8, is the number base of the number (here, octal 17). The parseFloat() Method The parseFloat() method is just like the parseInt() method except that it returns a floating-point number. A floating-point[3] number is a number that contains a fractional part, such as 3.0, –22.5, or .15. The decimal point is allowed in the string being parsed. If the string being parsed does not start with a number, NaN (not a number) is returned. if/else "You better pay attention now, or else . . . " Ever heard that kind of statement before? JavaScript statements can be handled the same way with the if/else branching construct. This construct allows for a two-way decision. The if evaluates the expression in parentheses, and if the expression evaluates to true, the block after the opening curly braces is executed; otherwise the block after the else is executed. if (condition){ statements1; } else{ statements2; } The while Loop The while statement executes its statement block as long as the expression after the while evaluates to true; that is, non-null, non-zero, non-false. If the condition never changes and is true, the loop will iterate forever (infinite loop). If the condition is false control goes to the statement right after the closing curly brace of the loop's statement block. The break and continue functions are used for loop control. while (condition) { statements; increment/decrement counter; } The for Loop The for loop consists of the for keyword followed by three expressions separated by semicolons and enclosed within parentheses. Any or all of the expressions can be omitted, but the two semicolons cannot. The first expression is used to set the initial value of variables and is executed just once, the second expression is used to test whether the loop should continue or stop, and the third expression updates the loop variables; that is, it increments or decrements a counter, which will usually determine how many times the loop is repeated. for (initialize; test; increment/decrement) {statement(s);} Calling a Function from a Link A function can be called directly from a link, by using the JavaScript pseudoprotocol, javascript:, instead of a normal URL. The javascript: protocol and the function call are placed within quotes and assigned to the href attribute of the <a> tag. When the user clicks his mouse on the link, instead of the program going to the URL of another page, a JavaScript function will be called. <html> <head> <title>Functions</title> <script language=javascript> function greetings(){ // Function defined within <head> tags document.bgColor="lightblue"; alert("Greetings to you!"); } </script> </head> <body><center> <a href="javascript:greetings()"><big>Click here for Salutations</big> </a><br> </center> </body> </html> Calling a Function from an Event An event is triggered when a user performs some action, like clicking on a button or moving his mouse over a link. The function assigned to the event is called an event handler. When the event is triggered, the function is called. In the following example, when the user clicks on the Welcome button, the function is called. <html> <head<title>Functions and Events</title> <script language=javascript> function greetings(){ // Function definition document.bgColor="pink"; alert("Greetings and Salutations! "); } </script> </head> <body><center> <form> <input type="button" value="Welcome button" onClick="greetings();" > </form> </body> </html> Array Properties and Methods Since an array is an object in JavaScript, it has properties to describe it and methods to manipulate it. The length of an array, for example, can be determined by the length property, and the array can be shortened by using the pop() method <html> <head> <title>Array Properties</title> <h2>Array Properties</h2> <script language="JavaScript"> var book = new Array(6); // Create an Array object book[0] = "War and Peace"; // Assign values to elements book[1] = "Huckleberry Finn"; book[2] = "The Return of the Native"; book[3] = "A Christmas Carol"; book[4] = "The Yearling"; book[5] = "Exodus"; </script> </head> <body bgcolor="lightblue"> <script language="JavaScript"> document.write("<h3>"); document.write("The book array has " + book.length + " elements<br>"); for(var i in book){ document.write("book[" + i + "] "+ book[i] + "<br>"); } </script> </body> </html> JavaScript and the forms Object Submitting a Form with JavaScript (Event Handlers) With onClick Event Handler <html><head><title>onClick Event Handler and Forms</title> <script language="JavaScript"> function readySubmit(){ if(confirm("Are you ready to submit your form? ")){ return true; } else{ return false; } } </script> </head> <body> <form action="/cgi-bin/testform.cgi" method="post"> Enter your user id: <input type="text" name="textbox" value=""> <br> Type your password: <input type="password" name="secret"> <p> <input type="submit" onClick="readySubmit();"> </body></html> With onSubmit Event Handler <html> <head><title>onSubmit Event Handler and Forms</title> <script language="JavaScript"> function readySubmit(){ if(confirm("Are you ready to submit your form? ")){ return true;} else{ return false;} } </script> </head> <body> <form action="/cgi-bin/testform.cgi" method="post" onSubmit="return(readySubmit());" > Enter your user id: <input type="text" name="textbox" value=""> <br> Type your password: <input type="password" name="secret"> <p> <input type="submit" > </body> </html> The this Keyword The this keyword is especially helpful when dealing with forms. The this keyword refers to the current object. For forms containing multiple items, such as checkboxes, radio buttons, and text boxes, it is easier to refer to the item with the this keyword than by using its full name when calling a function. When using an event handler, the this keyword always refers to the object that triggered the event. If the event is triggered from within the <form> tag, this refers to the current form, but if it is triggered by an element within the form, such as an input device, then it references that element. Each element has a form property that references the form in which it was created. In the following segment of an HTML document, note that when the onClick event handler is triggered within the first button input type, the form property is used to reference the form itself, whereas in the second button, the this keyword refers to the current button. FORMAT <form> <-- The JavaScript form object <input type="button" <-- This a JavaScript element value="Print Form Stuff" onClick="display_formval(this.form);" > <-- this keyword references the form object by using the element's form property <input type="button" value="Print Button Stuff" onClick="display_buttonval(this);" > <-- this keyword references the current object, the button </form> Example <html> <head><title>An HTML form and the "this" keyword and Event Handler</title> <script language="JavaScript"> function checkForm(yourinfo){ if(yourinfo.namestring.value == ""){ // Check for an // empty string alert("Please type in your name"); return(false); } else{ return(true); } } </script> </head> <body><b> <form name="info" action="/cgi-bin/bookstuff/form1.cgi" method="post" onSubmit="return checkForm(this)"><p> <font size="+1"><p> Type your name here: <input type="text" name="namestring" size="50"> <p> <input type="submit" value="Submit"> <input type="reset" value="Clear"> </form> </body> </html> How to Use Mouse Events The onMouseOver and onMouseOut event handlers occur when the user's mouse pointer is moved over or out of an object. The onMouseMove event occurs when the mouse just touches the object. In the following example, every time the user touches the button labeled onMouseMove with his mouse, a function called counter() is invoked to keep track of the number of mouse moves that have taken place. <html><head><title>Mouse Events</title> <script language="JavaScript"> var counter=0; function alertme(){ alert("I'm outta hea!"); window.close(); } function track_Moves(){ counter++; if(counter==1){ alert(counter + " mouse moves so far!"); } else{ alert(counter + " mouse moves so far!"); } } </script> </head> <body bgColor="CCFF00" onDblClick="alertme()";> <p><font face="arial" size=3> Double click anywhere on this page to get out! <p> When the mouse moves over the link, an event is triggered. <a href="#" onMouseOver="alert('Event: onMouseOver');">onMouseOver </a><p> When the mouse moves away from a link, an event is triggered. <a href="#" onMouseOut="alert('Event: onMouseOut');">onMouseOut </a><p> When the mouse moves in or out of the button, a function<br> is called that keeps track of how many times the mouse touched the button. <form> <input type="button" value="onMouseMove" onMouseMove="track_Moves();"> </form> </body> </html> Handling Key Events: onKeyPress, onKeyDown, and onKeyUp As of JavaScript 1.2, keyboard actions, not just mouse actions, can be detected in JavaScript programs. This is useful, for example, in certain types of game programs where keyboard entry must be detected to determine the next action. The onKeyPress, onKeyDown, and onKeyUp event handlers are triggered when the user presses a key and releases it. The onKeyPress event is a combination of two actions: after you press down on the key, the event happens just at the point you release it. The other two key events happen as soon as you press a key down (onKeyDown) and then when you release it (onKeyUp). The onKeyDown and onKeyPress events keep firing continuously as long as the user keeps a key depressed, whereas the onKeyUp event fires once when the user releases the key. Some browsers may differ in the way they handle key events. | Properties | Description | | altKey, ctrlKey, shiftKey | Boolean properties that indicate whether the Alt, Ctrl, Meta, and Shift keys were pressed at time of the event. | | metaKey | Boolean property that indicate whether the Meta key was pressed at the time of the event. NS/Firefox only. | | charCode | Property indicating the Unicode for the key pressed. Use String.fromCharCode(charCode) to convert code to string. NS/Firefox only. | | keycode | Property indicating the Unicode for the key pressed. Use String.fromCharCode(keyCode) to convert code to string. | | type | A string indicating the type of event, such as "mouseover", "click", etc. | | which | Legacy property indicating the Unicode for the key pressed. Identical to "charCode", except this property works in NS4 as well. NS/Firefox only. | Green properties- NS/ Firefox exclusive. As you can see, some properties of the Event object for the keyboard are shared (those that are white), while others are exclusive to either Firefox. However, they all serve the same function. You're probably still confused at this point, but nothing a few examples can't help clear up. In the first example, I'll detect and alert the Unicode of any key pressed: <script type="text/javascript"> function displayunicode(e){var unicode=e.keyCode? e.keyCode : e.charCode alert(unicode) } </script> <form> <input type="text" size="2" maxlength="1" onkeyup="displayunicode(event); this.select()" /> </form> This alerts the unicode of the character pressed. But of course it'd be much better if we can find out the actual key that was pressed. This is where String.fromcharCode() is useful: <script type="text/javascript"> function textsizer(e){var evtobj=window.event? event : e //distinguish between IE's explicit event object (window.event) and Firefox's implicit. var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode var actualkey=String.fromCharCode(unicode) if (actualkey=="a") document.body.style.fontSize="120%" if (actualkey=="z") document.body.style.fontSize="100%" } document.onkeypress=textsizer </script> Using the onkeypress event, we could create on-the-fly form validation. Now that's something CGI most certainly can't do. The idea is to use the onkeypress event handler inside the form field to check, so as the user types, it is being validated concurrently. Numbers only Here's an example that limits a form field to contain only numeric input (on the fly, of course!). <script type="text/javascript"> function numbersonly(e){var unicode=e.charCode? e.charCode : e.keyCode if (unicode!=8){ //if the key isn't the backspace key (which we should allow)if (unicode<48||unicode>57) //if not a number return false //disable key press } } </script> <form> <input type="text" size=18 onkeypress="return numbersonly(event)"> </form> Try typing in stuff other than numbers into the above box- you can't. How does the script work? By checking to see whether the keycode of the key pressed as the user types falls within the range of the number keys (48~57), and if not, returns false, which disables the keypress action. How did I know 48 to 57 represents the keycode of the numeric keys? Well, by using a simple alert(event.keycode) script to map it out (no fancy tricks here). Then, by using the "onkeypress" event handler, along with function numbersonly() inside the textbox to validate, we have one picky box! Limit number of characters allowed <script type="text/javascript"> function limitlength(obj, length){var maxlength=length if (obj.value.length>maxlength) obj.value=obj.value.substring(0, maxlength) } </script> Enter text (max length is 20 characters): <form> <textarea onkeyup="return limitlength(this, 20)" style="width: 300px; height: 90px"></textarea> </form> getElementById() Method All that node stuff can be really tricky and vary on different browsers, but by combining the HTML id attribute with the getElementById() method of the document object, it is much easier to get a handle on any HTML object. The getElementById() method returns a reference to the HTML element that can then be manipulated by a JavaScript program. Suppose you have a <body> tag defined with an id attribute, as: <body id="bdy1"> Now in JavaScript you can reference the body element with the getElementById() method as follows: bdyreference = document.getElementById("bdy1") The style Object and CSS The style object contains a set of properties corresponding to the CSS attributes supported by your browser. Each HTML object has a style property (starting with IE4 and NN6) used to access the CSS style attributes assigned to it; for example, an H1 element may have been defined with a CSS font-style, color, and padding. The style object has properties to reflect each of the CSS atributes. See Table 15.15. Many of the CSS style attributes, such as background-color, font-size, and word-spacing, contain hyphens in their names. Like all objects we have seen in JavaScript, there is a convention for spelling the name of the object. The name would not contain a hyphen, and multiple words after the first word are usually capitalized. Therefore, the CSS naming convention is different with the properties of the style object. The hyphen is removed and the first letter of each word after the hypen is capitalized. For example, the CSS attribute, background-color, when used as a style property, is spelled backgroundColor, font-size is fontSize, and border-right-width is borderRightWidth. <html> <head><title>Changing Background Color Dynamically</title> <script language="JavaScript"> function bodyColor(){ var i = document.form1.body.selectedIndex; bodycolor = document.form1.body.options[i].value; document.getElementById("bdy").style.backgroundColor = bodycolor; } </script> </head> <body ID="bdy"> <p> Pick a background color for this page. </p> <form name="form1"> <b> Color </b> <select name="body" onChange="bodyColor();"> <option value="pink">pink</option> <option value="lightblue">blue</option> <option value="yellow">yellow</option> <option value="lightgreen">green</option> </select> <br> </form> <p> This is a test. </p> </body> </html> Changing Color with the className Property The className property is defined for all HTML elements. With the className property, you can change an element dynamically by assigning it the name of a class defined in a CSS. The following example contains a cascading style sheet with three classes. <html><head><title>Coloring Text</title> <style type="text/css"> body { background-color: yellow; font-size: 22pt; font-weight: bold; } .red { color:rgb(255,0,0); /* Defining classes */ font-style: verdana; font-size: 32; } .blue { color:blue; font-style: verdana; font-size: 36; } .green { color: green; font-style: verdana; font-size: 40; } </style> <script language="javascript"> function init(){ div1=document.getElementById("first"); div2=document.getElementById("second"); div3=document.getElementById("third"); } function colorText(){ div1.style.left = 50; div1.style.top = 50; div1.className="red"; div2.style.left = 100; div2.style.top = 100; div2.className="blue"; div3.style.left = 150; div3.style.top = 150; div3.className="green"; } </script> </head> <body onLoad="init()"> <div id="first" style="position:absolute; top:50px">It's a one,</div> <div id="second" style="position:absolute; top:100px">and a two,</div> <div id="third" style="position:absolute; top:150px">and three!</div> <form> <input type="button" value="move and color text" onClick="colorText()"> </form> </body> Drop-Down Menus Drop-down menus are commonly used in Web pages to create submenus that appear and then disappear when no longer needed. The following example demonstrates the use of the visibility property to create this type of menu. When the user clicks on one of the links in the main menu, a drop-down menu will appear. If he double-clicks anywhere within the drop-down menu, it will be hidden from view. Each of the drop-down menus is defined within a <div> container. <html><head><title>Drop-Down Menu</title> <style type="text/css"> a { font-family: verdana, arial; color: darkblue; font-weight: bold; margin-left: 4px; } /*link style for main menu*/ #menu, .menu { font-stye: verdana; font-size:10pt; color:black; } /* link style for drop-down menu */ #menu { position:absolute; top:40px; border-style:solid; border-width:1px; padding: 5px; background-color:yellow; width:75px; color: black; font-size: 12pt; visibility:hidden; } #menu2 { position:absolute; top:40px; left:3.2cm; border-style:solid; border-width:1px; padding: 5px; background-color:orange; width:80px; color: black; font-size: 12pt; visibility:hidden; } #menu3 { position:absolute; top:40px; left:6.2cm; border-style:solid; border-width:1px; padding: 5px; background-color:pink; width:80px; color: black; font-size: 12pt; visibility:hidden; } </style> <script language="JavaScript"> function showMenu(id){ var ref = document.getElementById(id); ref.style.visibility = "visible"; // Make the drop-down // menu visible } function hideMenu(id){ var ref = document.getElementById(id); ref.style.visibility = "hidden"; // Hide the drop-down menu } </script> <body bgColor="lightblue"> <table width="350" border="2" bgcolor="lightgreen" cellspacing="1" cellpadding="2"> <tr> <td width="100"> <div id="menu" onDblClick="hideMenu('menu');"> <a class="menu" href="#">US</a><br> <a class="menu" href="#">World</a><br> <a class="menu" href="#">Local </a><br> </div> <a href="#" onMouseOver="showMenu('menu');hideMenu('menu2');hideMenu('menu3');">News</a> </td> <td width="100"> <div id="menu2" onDblClick="hideMenu('menu2');"> <a class="menu" href="#">Basketball</a><br> <a class="menu" href="#">Football</a><br> <a class="menu" href="#>">Soccer</a><br> </div> <a href="#" onMouseOver="showMenu('menu2');hideMenu('menu');hideMenu('menu3');">Sports</a> </td> <td width="100"> <div id="menu3" onDblClick="hideMenu('menu3');"> <a class="menu" href="#">Movies</a><br> <a class="menu" href="#">Plays</a><br> <a class="menu" href="#>">DVD's</a><br> </div> <a href="#" onMouseOver="showMenu('menu3');hideMenu('menu');hideMenu('menu2');" >Entertainment</a> </td> </tr></table> </body> </html> Javascript Popups Chances are if you are reading this web page then you have experienced hundreds of Javascript popup windows throughout your web surfing lifetime. Want to dish out some pain of your own creation onto unsuspecting visitors? I hope not! Because web sites with irrelevant popups are bad! However, we will show you how to make windows popup for reasonable occasions, like when you want to display extra information, or when you want to have something open a new window that isn't an HTML anchor tag <a>. Javascript window.open Function The window.open() function creates a new browser window, customized to your specifications, without the use of an HTML anchor tag. In this example we will be making a function that utilizes the window.open() function. <head> <script type="text/javascript"> <!-- function myPopup() {window.open( "http://www.google.com/" ) } //--> </script> </head> <body> <form> <input type="button" onClick="myPopup()" value="POP!"> </form> <p onClick="myPopup()">CLICK ME TOO!</p> </body> This works with pretty much any tag that can be clicked on, so please go ahead an experiment with this fun little tool. Afterwards, read on to learn more about the different ways you can customize the Javascript window that POPS up. Javascript Window.Open Arguments There are three arguments that the window.open function takes. First the relative or absolute URL of the web page to be opened. Secondly, a text name for the window, and lastly a long string that contains all the different properties of the window. Naming a window is very useful if you want to manipulate it later with Javascript. However, this is beyond the scope of this lesson and we will instead be focusing on the different properties you can set with your brand spanking new Javascript window. Below are some of the more important properties. - dependent - Subwindow closes if parent(the window that opened it) window closes
- fullscreen - Display browser in full screen mode
- height - The height of the new window, in pixels
- width - The width of the new window, in pixels
- left - Pixel offset from the left side of the screen
- top - Pixel offset from the top of the screen
- resizable - Allow the user to resize the window or prevent resizing
- status - Display the status bar or not
Dependent, fullscreen, resizable, and status are all examples of ON/OFF properties. You can either set them equal to zero to turn them off, or set them to one to turn them ON. There is no inbetween setting for these types of properties. Upgraded Javascript Popup Window! Now that we have the tools, let's make a sophisticated Javascript popup window that we can be proud of. <head> <script type="text/javascript"> <!-- function myPopup2() {window.open( "http://www.google.com/", "myWindow", "status = 1, height = 300, width = 300, resizable = 0" ) } //--> </script> </head> <body> <form> <input type="button" onClick="myPopup2()" value="POP2!"> </form> <p onClick="myPopup2()">CLICK ME TOO!</p> </body> Now that is a prime example of a worthless popup! When you make your own, try to have them relate to your content, like a small popup that has no navigation that just gives the definition or explanation of a word, sentence, or picture! Javascript Print Function The Javascript print function performs the same operation as the print option that you see at the top of your browser window or in your browser's "File" menu. The Javascript print function will send the contents of the webpage to the user's printer. Many believe this function to be worthless, but there are many computer users that do not know their way around a computer all that well and it can sometimes create a more user friendly experience when you provide as many helpful features as possible. Javascript Print Script - window.print() The Javascript print function window.print() will print the current web page when executed. In this example script we will be placing the function on a Javascript button that will perform the print operation when the onClick event occurs. <form> <input type="button" value="Print This Page" onClick="window.print()" /> </form> Javascript innerHTML Ever wonder how you could change the contents of an HTML element? Maybe you'd like to replace the text in a paragraph to reflect what a visitor has just selected from a drop down box. By manipulating an element's innerHtml you'll be able to change your text and HTML as much as you like. Changing Text with innerHTML Each HTML element has an innerHTML property that defines both the HTML code and the text that occurs between that element's opening and closing tag. By changing an element's innerHTML after some user interaction, you can make much more interactive pages. However, using innerHTML requires some preparation if you want to be able to use it easily and reliably. First you must give the element you wish to change an id. With that id in place you will be able to use the getElementById function which works on all browsers. After you have that setup you can now manipulate the text of an element. To start off with, let's try changing the text inside a bold tag. <script type="text/javascript"> function changeText(){ document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';} </script> <p>Welcome to the site <b id='boldStuff'>dude</b> </p> <input type='button' onclick='changeText()' value='Change Text'/> You now know how to change the text in any HTML element, but what about changing the text in an element based on user input? Well if we combine our knowledge from above with a text input... Updating Text Based on User Input By adding a Text Input we can take the update our bold text with whatever the user types into the text input. Note: We updated the function a bit and set the id to boldStuff2. <script type="text/javascript"> function changeText2(){ var userInput = document.getElementById('userInput').value; document.getElementById('boldStuff2').innerHTML = userInput;} </script> <p>Welcome to the site <b id='boldStuff2'>dude</b> </p> <input type='text' id='userInput' value='Enter Text Here' /> <input type='button' onclick='changeText2()' value='Change Text'/> Changing HTML with innerHTML You can also insert HTML into your elements in the exact same way. Let's say we didn't like the text that was display in our paragraph and wanted to updated it with some color. The following code will take the old black text and make it bright white. The only thing we're doing different here is inserting the html element span to change the color. <script type="text/javascript"> function changeText3(){ var oldHTML = document.getElementById('para').innerHTML; var newHTML = "<span style='color:#ffffff'>" + oldHTML + "</span>"; document.getElementById('para').innerHTML = newHTML;} </script> <p id='para'>Welcome to the site <b id='boldStuff3'>dude</b> </p> <input type='button' onclick='changeText3()' value='Change Text'/> This was a pretty simple example of changing the HTML of an element. All we did was take the old text that was in the paragraph tag and surround it in a span tag to change the color. However, there are many more things you can do by changing an element's HTML, so don't forget this useful tool!
|
Kuliah TKI - Blog da...
mm Apparently, 21,000 boots imported by
Clas-class php yang ...
mm Apparently, 21,000 boots imported by
Kuliah TK Internet :...
mm Apparently, 21,000 boots imported by
The Power of GIS - U...
mm Apparently, 21,000 boots imported by
Kuliah TK Internet :...
mm Apparently, 21,000 boots imported by
JPGraph - membuat gr...
timberland - mm Apparently, 21,000 bo...
Kuliah TKI : Ajax - ...
mm Apparently, 21,000 boots imported by
Banner spesial untuk...
mm Apparently, 21,000 boots imported by