Things to Do with JavaScript Things to Do with JavaScript • • • • • • Auto email with reset confirm Auto email with data validation and autofocus Rename a button Change background color View URL Open a window 2 copyright Penny McIntire, 2013 Things to Do with JavaScript • • • • • • • Display date Print page Save and access a cookie Sniff the browser Data validation Preload images FlyoutDropdown menus 3 copyright Penny McIntire, 2013 Auto Email • You can create an html form, then automatically email the data captured from the form… JSAutoEmail.html 4 copyright Penny McIntire, 2013 <html><head><title>Autoemail</title> <script language="JavaScript"> function allowReset() { return window.confirm(“Clear the form?") } </script> </head> 5 copyright Penny McIntire, 2013 action = “mailto:… <body> <form method=post action="mailto:pmcintire@niu.edu?subject=Prospective Customer& body=Some standard message could go here" onReset="return allowReset()" enctype = "text/plain"> Executes the function allowReset to double check. <p>Enter your first name:</p> <input type="text" name="firstName" value = "Penny"><p> Enter your last name: <input type="text" name="lastName" value = "McIntire"><p> <input type="radio" name="gender" value = "male" checked>Male <input type="radio" name="gender" value = "female">Female <p> <input type="checkbox" name="retired">I am retired<p> <input type="reset"> <input type="submit" value = "Submit this now!"></form> 6 </body> copyright Penny McIntire, 2013 </html> Auto Email • This confirms the reset before clearing the form. • If the function returns true, it resets. • If the function returns false, it does not. • onSubmit works the same way, to interrupt the process before sending the form to the server. 7 copyright Penny McIntire, 2013 Auto Email • “Secret” email should never be used, and, in fact, modern versions of browsers don’t allow secret email; a window is displayed asking user permission. • There seems to be an upper limit of 2044 characters for the content of an auto email. 8 copyright Penny McIntire, 2013 Auto Email with Editing and Autofocus • Now let’s simplify the email part and check for empty fields as well as autofocus on appropriate fields… JSAutoEmail2.html 9 copyright Penny McIntire, 2013 <html><head><title>Auto Email with Editing and Autofocus</title> <script language="JavaScript"> function submitForm() { if (document.loginForm.firstName.value == "" && document.loginForm.lastName.value == "") { Sets focus alert( "Please enter your first and last names"); on empty document.loginForm.firstName.focus(); field. return false; } else if(document.loginForm.firstName.value == "") { alert( "Please enter your first name"); document.loginForm.firstName.focus(); return false; } else if(document.loginForm.lastName.value == "") { alert( "Please enter your last name "); document.loginForm.lastName.focus(); return false; “Return false;” aborts } else { the “submit” part of return true; “Return true;” autosubmit. 10 } submits the email. copyright Penny McIntire, 2013 } </script></head> Sets focus on first field, when page opens. onSubmit captures the submit and sends it to the function. A false return aborts the autoemail. <body onLoad="document.loginForm.firstName.focus();"> <h1>Auto Email with Editing and Autofocus</h1> <form name="loginForm" method=post action="mailto:pmcintire@niu.edu" enctype = "text/plain" onSubmit="return submitForm()"> <p>Enter your first name: <input type="text" name="firstName"></p> <p>Enter your last name: <input type="text" name="lastName"></p> <input type="submit"></p> 11 </form></body></html> copyright Penny McIntire, 2013 Rename a Button JSRenameButton .html 12 copyright Penny McIntire, 2013 <html><head> <script language = "JavaScript"> function getButtonName() { var newName = prompt("Rename the button, please") document.myForm.myButton.value=newName } </script> Tracing through the Replaces the old value </head> DOM with the new one. <body> <form name = "myForm"> <input type = "button" name = "myButton" value = “Click to rename me" onClick="getButtonName()"> </form> </body></html> Sets up the button. 13 copyright Penny McIntire, 2013 Change Background Color JSChangeBackground.html 14 copyright Penny McIntire, 2013 <html><head> <script language = "JavaScript"> function newBackColor(color) { if (color == 1) {document.bgColor="red"} if (color == 2) {document.bgColor="green"} if (color == 3) {document.bgColor="blue"} } </script> </head> Changes the document property “bgColor” <body> <h1>We love color!</h1> <form> To change the background color, click on a button below:<br><br> <input type = "button" value = "red" onClick = "newBackColor(1)"> <input type = "button" value = "green" onClick = "newBackColor(2)"> <input type = "button" value = "blue" onClick = "newBackColor(3)"> </form></body></html> 15 copyright Penny McIntire, 2013 View URL JSViewURL.html 16 copyright Penny McIntire, 2013 <html><head> <script language = "JavaScript"> function getURL () { alert(“You are in document: " + document.location) } </script> </head> <body> <h1>We love URLs!</h1> <form> To find out your current URL:<br><br> <input type = "button" value = "Show Me URL" onClick = “getURL()"> </form> </body></html> 17 copyright Penny McIntire, 2013 Open a Window JSOpenNewWindow.html 18 copyright Penny McIntire, 2013 <html><head><script language = "JavaScript"> function myNewWindow() { window.open("http://www.niu.edu", "newWindow", "height=100,width=100,status=yes"); newWindow.focus(); } (“URL”, “window name”, </script></head> “parameters”) See page 885 of DHTML. <body> <h1>Open New Window</h1> <form name = "myForm"> <input type = "button" value = "Open Window" onClick = "myNewWindow()"> </form> 19 </html> copyright Penny McIntire, 2013 Display Date JSDisplayDate.html 20 copyright Penny McIntire, 2013 If “new Date” with no <html><head> constructors, it gets <script language = "JavaScript"> today’s date. var myDate = new Date(); var myDay=myDate.getDate(), //day number in month myDayOfWeek=myDate.getDay(), //day number in week myMonth=myDate.getMonth(), //month number myYear=myDate.getFullYear(); //year number switch (myDayOfWeek) { case 0: dayName = "Sunday"; break; case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; case 4: dayName = "Thursday"; break; case 5: dayName = "Friday"; break; default: dayName = "Saturday"; break; } getYear method is unpredictable in earlier browsers because of Y2K 21 copyright Penny McIntire, 2013 switch (myMonth) { case 0: monthName = "January"; break; case 1: monthName = "Februrary"; break; case 2: monthName = "March"; break; case 3: monthName = "April"; break; case 4: monthName = "May"; break; case 5: monthName = "June"; break; case 6: monthName = "July"; break; case 7: monthName = "August"; break; case 8: monthName = "September"; break; case 9: monthName = "October"; break; case 10: monthName = "November"; break; default: monthName = "December"; } </script> 22 </head> copyright Penny McIntire, 2013 <body> <script language = "JavaScript"> document.writeln("The system date looks like this..." + myDate +"<br>") document.writeln("Today's date is: " + dayName + ", " + monthName + " " + myDay + ", " + myYear + "<br>") </script> </body> </html> 23 copyright Penny McIntire, 2013 Printing a Page • To print a page… <a href="#" onClick="window.print();"> Print this page </a> 24 copyright Penny McIntire, 2013 Cookies • As your web application executes and links from page to page, it can be important to keep track of various pieces of information. • E.g., you might want to display a user’s login name on a page linked to later. • Or you could save the login to access when a user returns days later. 25 copyright Penny McIntire, 2013 Cookies • Traditional (non-web) applications have no trouble with this “keeping state” or handling “persistence” – they aren’t hopping from page to independent page, and even if they were, they would simply write important data out to disk. 26 copyright Penny McIntire, 2013 Cookies • It’s not so easy with web applications. – Each document is independent and can’t easily communicate with another document. – “Writing out to disk” means hitting the server, which is time consuming, and it might mean storing thousands of entries on the server per day, which eats up disk space rapidly. 27 copyright Penny McIntire, 2013 Cookies • So, we have cookies. • Think of them as special, hidden cookie jars, kept on the client, in which the client or the server can drop tidbits of information for later retrieval from a second, independent webpage. page1.html page2.html Local Storage 28 copyright Penny McIntire, 2013 Cookies • Examples of cookie use: – When a web site remembers your name or password. – When a shopping cart remembers what you have already chosen as you browse from page to page. 29 copyright Penny McIntire, 2013 Cookies • There are some limitations to cookies: – A standard web browser can retain at least 300 cookies – some browsers go as high as 3000 or even unlimited. – Mobile browsers only 50 cookies? – At least 20 may be “owned” by a given domain (e.g., cs.niu.edu could store at least 20 cookies on a visitor’s computer). – Each cookie must be under 4K in length, 2K for older browsers. 30 copyright Penny McIntire, 2013 Cookies • You may be able to open your cookie files (just regular text files), in your temporary internet files (wherever the heck they may be located on your particular machine + operating system) 31 copyright Penny McIntire, 2013 Cookies • Cookies store: – The domain name that created the cookie. – Whether the server or JavaScript within the browser stored the cookie. – Whether or not the cookie should be transported using SSL. – The expiration date. – The name and value pair that you want to store in the cookie… 32 copyright Penny McIntire, 2013 Cookies – For instance, if you want to save the user’s first name, you might have a name/value pair like firstName= Penny. 33 copyright Penny McIntire, 2013 Cookies • The format of the string used to set a cookie is as follows: document.cookie = ‘myNewCookie=value you have assigned’ + ‘expires=Friday, 30-Mar-2001 23:59:59 GMT;’ – This leaves a cookie with the name myNewCookie, with the value “value you have assigned”, which expires on March 30 at 1 second before midnight. – Let’s look at the individual parts here… 34 copyright Penny McIntire, 2013 Cookies – The name and value parts are required. – No semicolons, commas, or blanks in the whole “name” part, OR • • Encode the value part of the pair with the JavaScript escape() function to take care of any special characters. Use the unescape() function later, when retrieving the cookie, to get back to the original characters. – If two cookies have the same name, the new one overwrites the old one. 35 copyright Penny McIntire, 2013 Cookies • ‘expires=Friday, 30-Mar-2001 23:59:59 GMT;’ – Can use the JavaScript Date object format shown here, or use a calculation for the date and time in milliseconds since January 1, 1970, GMT. – If this is omitted, the cookie expires automatically at the end of the session. 36 copyright Penny McIntire, 2013 Cookies • The code is a little more complicated than what is shown, especially retrieving the cookie from the second page that actually needs it – the single line that creates the cookie has to be wrapped in more JavaScript to see if a cookie exists and to parse the cookie. • Example and code from W3C: http://www.w3schools.com/JS/js_cookies. 37 asp copyright Penny McIntire, 2013 Local Storage • localStorage: an alternative to cookies that can store data locally within the user’s browser. • More secure than cookies. • Larger amounts of data (up to 5 MB). • Doesn’t hit the server. • All pages from the same domain can store and access the same data. 38 copyright Penny McIntire, 2013 localStorage • To embed localStorage in the first page: localStorage.setItem("lastName", "Smith"); • To retrieve localStorage in the second page: document.getElementByID("myResult").innerHTML= localStorage.lastName; Where to put the value “Smith” 39 copyright Penny McIntire, 2013 Sniffing the Browser and Version • There are lots of scripts floating around to check for the browser type and version. • If you check this, you can write completely different versions of the page for the different browsers. • But, is this a good thing??? – A maintenance nightmare to avoid (almost) at all costs – rarely needed these days 40 anyway. copyright Penny McIntire, 2013 Sniffing the Browser and Version • If you really must include something for a particular environment, if might be better to have just a single document, with small areas that check for the browser, rather than having two completely different pages. 41 copyright Penny McIntire, 2013 Sniffing the Browser and Version • Can instead check to see if a particular feature that you’re using is supported – less of a problem, still not ideal. • Examples: if (document.layers) //Navigator <6.0 if (window.opera) //Opera • In any case, there is code out there that you can download to do the sniffing, but I can’t find anything recent 42 other than in the Jquery library. copyright Penny McIntire, 2013 Data Validation • “Your task is to anticipate every possible entry that users could make and let through only those your scripts can use.” Danny Goodman • Also, use checkboxes and radio buttons whenever possible, to ensure that invalid data entry doesn’t occur. 43 copyright Penny McIntire, 2013 Data Validation • Verifying just before the form is submitted: – Use the onSubmit = event on the form to execute a function that does final validation. 44 copyright Penny McIntire, 2013 Preloading Images • Preload images – When a user mousesover a button for the first time, the mouseover effect could take a while to show up if it has to wait for the image to download. – As an alternative, download all of the images for the page when the page itself downloads, so they are all ready and waiting. – Code for this is automatically done by Dreamweaver unless you deliberately tell it 45 not to add the code… copyright Penny McIntire, 2013 Preloading Images function MM_preloadImages() • Good luck understanding Dreamweaver’s code. Nonetheless, it works. • Essentially, onLoad in the <body> calls the function to reference each image that doesn’t appear on the original page (like rollover images), which forces a download of the image right then, instead of waiting until the user mouseovers. 46 copyright Penny McIntire, 2013 Flyout/Drop Down Menus • Three easy (?) ways to do this: – Use Dreamweaver’s Show/Hide Layers; i.e., create semi-manually. – On older copies of Dreamweaver: Window > Behaviors > Spry Menu Bar to create automatically. • Still need to tweak the CSS so that the dropdowns fit with the look of your page. 47 copyright Penny McIntire, 2013 Flyout/Drop Down Menus – On newer copies of Dreamweaver, use a framework like JQuery or widgets: • Insert > Widgets > Widget Browser to add the appropriate JQuery menu widgets (lots of choices) to Dreamweaver (must create a free account). Click on image to get live previews and view code. • Widget help: http://helpx.adobe.com/dreamweaver/using/jq uery-widget-dreamweaver.html and http://tv.adobe.com/watch/learndreamweaver-cc/using-jquery-widgets-in-web48 pages-in-dreamweaver/ copyright Penny McIntire, 2013 Resources • HTML5 Cross browser list of polyfills (fills a hole in a browser), shims (fixing something automatically, like putting a transparent gif in all empty <td>s automatically), and fallbacks (degrading gracefully) https://github.com/Modernizr/Modernizr /wiki/HTML5-Cross-Browser-Polyfills 49 copyright Penny McIntire, 2013 Resources • Modernizr, a JavaScript library that detects HTML5 and CSS3 features in the user’s browser http://modernizr.com/ • Dojo, a toolkit for fast development http://dojotoolkit.org/ 50 copyright Penny McIntire, 2013 Resources • JQuery, a fast, small, and feature-rich JavaScript framework/library, including multiple styles of dropdown/flyout menus. http://jquery.com/ and how it works http://learn.jquery.com/aboutjquery/how-jquery-works/ ) 51 copyright Penny McIntire, 2013 Resources • JQuery can do things like: – A cool color picker. – Slide shows. – CSS rollover buttons. – Calendar/date picker. – Image magnifiers. – Chart generator based upon HTML table data. 52 copyright Penny McIntire, 2013 Resources – Slider bar generator. – Menu of images that enlarge on mouseover – i.e., mimics a Mac menu bar. – Table manipulation: sort, resizeable columns, etc. – YouTube viewer. – Weather updater. – Lots, lots more, growing by the day. 53 copyright Penny McIntire, 2013 Resources – Testing help: Selenium, a suite of tools to automate testing in browsers. Can do even non-JavaScript things like checking all the links in your site to see if any are broken. http://docs.seleniumhq.org/ 54 copyright Penny McIntire, 2013