name = name.replace(/</g, "<").replace(/>/g, ">");
Current Window | self, window, parent, top (Window objects) | |||
navigator | ||||
frames[] | ||||
location | ||||
history | ||||
screen | ||||
document | anchors[] | |||
links[] | ||||
images[] | ||||
applets[] | ||||
forms[] | elements[] | options |
event handler | onclick |
|
onmousedown |
| |
onmouseup |
| |
onmouseover |
| |
onmouseout |
| |
onchange |
| |
onload |
| |
onunload |
| |
<input type=checkbox name=options value=blah onclick="blah = this.checked;";function testalert() { alert("testing..."); } <a href="" onclick="testalert(); return(false);">test alert</a>test alert //can also assign event handler from external javascript code... | ||
Javascript in URLs |
<a href="javascript:alert("Hello World!");">test alert</a> test alert <a href="javascript:window.open('about:blank'); void 0;">open new win</a> open new win // adding urls this way not considered good form (don't modify link characteristics). // you can also type the javascript url into the location field of the browser | |
bookmarklets |
| |
//put the following into a link <a href='javascript:var e="",r="";do{e=prompt("Expression: "+e+"\n"+r+"\n",e);try{r="Result: "+eval(e);}catch(ex){r=ex;}}while(e);void 0;'>JS Evaluator</a> //search for bookmarklets on the web |
...in html <body> section... <!--[if IE]> html displayed in IE (only) <![endif]--> <!--[if gte IE 6]> html displayed in IE6+ (only) <![endif]--> <!--[if !IE]> <--> display in browsers other then IE <!--> <![endif]--> display in all browsers
/*@cc_on @if (@_jscript) // jscript is IE javascript // var is always set in IE @else*/ //no longer insid a JavaScript comment //but still in the IE conditional comment //non-IE browsers will run this code /*@end @*/
setTimeout() | schedules function to function to run after number of milliseconds
|
function alertinfive() { track5 = setTimeout("alert('5 seconds later')",5000); return(false); }; <form><input type="button" value="run in 5 seconds" onclick='alertinfive();'></form> | |
clearTimeout() |
<form><input type="button" value="cancel alert" onclick='clearTimeout(track5); return(false);'></form> |
setInterval() | function is invoked repeatedly at intervals of specified number of milliseconds put in example... |
clearInterval() | use the tracking value to clar the setInterval() put in example... |
location property | holds the URL of the current doc
| |
reload() | reloads currently diplayed page from the web server | |
replace() | loads and displays URL specified, and replaces current URL in browser's history list | |
href | ||
protocol | ||
host | ||
pathname | ||
search | items following a question mark in the URL (i.e. parameters) | |
document.write(location.href.toString() + " - " + location.protocol.toString()); |
history | back() | go back in history list |
forward() | go forward in history list | |
go() | takes integer arg. Goes forward or backward number of steps in history list. | |
Mozilla browsers support window.back() and window.forward(). Similar functionality, but may perform different action when used with frames. |
location | ||||
non-IE | default IE | IE doc with <!DOCTYPE> declaration | (all vars are read only) | |
window. | document.body. | document.documentElement. | outerWidth, outerHeight | size of browser win on desktop |
screenX, screenY screenLeft, screenTop (IE) | position of browser win on desktop | |||
innerWidth, innerHeight clientWidth, clientHeight (IE) | window size minus menu bars, toolbars, scrollbars, etc. | |||
pageXOffset, pageYOffset scrollleft, scrollTop (IE) | scrollbar positions | |||
scrollWidth, scrollHeight (IE) | size of doc |
function windowpos() { var windowX = 0; var windowY = 0; if (window.screenLeft) { //IE and others windowX = window.screenLeft; windowY = window.screenTop; } else if (window.screenX) { windowX = window.screenX; windowY = window.screenY; } var string6 = "windowX - " + windowX + ", windowY - " + windowY; alert(string6); } <form><input type="button" value="Window Location" onclick='windowpos();'></form>
width, height | specify size in pixels. |
availWidth, availHeight | specify display size actually available. |
availLeft, availTop (non IE) | first avail position on the screen. |
function screendim() { var string7 = "width - " + screen.width + ", height - " + screen.height; string7 += ", availWidth - " + screen.availWidth; string7 += ", availHeight - " + screen.availHeight; alert(string7); } <form><input type="button" value="Screen Dimensions" onclick='screendim();'></form>
var string7; for(var prop in navigator) string7 += prop + ": " + navigator[prop] + "
"; document.write(string7);
.open |
|
var w = window.open("urltoopen.html", "nameofwindow", "width=400,height=350,resizable=yes...(features), "true(default)/false - create new entry in (other) target windows browsing history"); | |
.close |
|
moveTo(), moveBy(), resizeTo(), resizeBy() | window geometry and placement manipulation. Considered bad form to use them. May be blocked or restricted by browsers. |
focus() | requests system give window keyboard focus,and move window to top of stacking order |
blur() | relinquishes keyboard focus |
scrollBy() | scross doc number of pixels left, right, up or down |
scrollTo() | scrolls doc to an absolute position
|
.location.hash | window.location.hash = "#blah" //will jump to the related <a name=> tag |
alert() | |
confirm() | confirm box blocks until user closes |
prompt() | prompt box blocks until user closes |
//display no more then 3 error msgs in dialog box window.onerror = function(msg, url, line) { if (onerror.num++ < onerror.max) { alert("ERROR: " + msg + "\n" + url + ":" + line); return true; } } onerror.max = 3; onerror.num = 0;
daname="joe"; document.writeln("hello "); //puts a newline in, good for <pre>>s document.write("there " + daname + "<br />"); hi = "hello "; over = "there "; document.write(hi, over, daname); //create/write to another doc in a another window var ww = window.open(); var dd = ww.document; dd.open(); //optional dd.write("hello"); //write into the doc in the other window dd.close(); //make sure to close the doc or it may not display
bgColor | background color of doc. <body> bgcolor attr |
cookie | http cookies |
domain | used to relax the same-origin security policy somewhat |
lastModified | contains mod date of doc |
location | deprecated. User URL prop. |
referrer | URL of doc containing link that brought the browser to curr doc |
title | <title> of doc |
URL | URL from which doc was loaded. Sames a window.location.href except in server redirect. |
anchors[] | <a> tag names. .name prop holds name attributes.
//example of getting text from anchors var a = document.anchors[0]; var text = null; if (a.text) text = a.text; // Netscape 4 else if (a.innerText) text = a.innerText; // IE 4+ if ((text == null) || (text == '')) text = a.name; // Default |
applets[] | Java applets |
forms[] |
|
images[] | src (r/w) property of <img> elements. Used for image-rollovers, simple animations... |
links[] |
|
position | static | relative | absolute | fixed |
top, left | |
bottom, right | |
width, height | |
z-index | |
display | inline | block | inline-block | ... |
visibility | visible | hidden | collapse |
clip | |
overflow | visible | hidden | scroll | auto |
margin, border, padding | |
background | |
opacity | How opaque or translucent. CSS3. Alternative exists for IE |
static | normal flow |
absolute | positioned independent of other elements. Not part of flow. IE4 only supports absolute positioning of certain elements. |
fixed | positioned with respect to browser window. Not part of flow |
relative | position adjusted relative to position in normal flow. normal flow space maintained |
<div style="position: relative; left: 0px; top: 0px; border: 1px solid black; height: 100px; width: 100px;"> <div style="position: absolute; left: 20px; top: 30px; height: 40px; width: 40px; background-color: blue;"> </div> </div>
element.offsetLeft | X (left) coord relative to (usually)offsetParrent | |
element.offsetTop | X (top) coord relative to (usually)offsetParrent | |
element.offsetWidth | (width) | |
element.offsetHeight | (height) |
//this example taken directly from JavaScript: The Definitive Guide //(5th edition) by David Flanagan. //different browsers handle offsetParent differently, but the following //should generally work to determine absolute position of element. //doesn't handle overflow attr - check the book for more //get x coord of element e function getX(e) { var x = 0; while(e) { x += e.offsetLeft; e = e.offsetParent; //move up to parent } return x; }
/* css */ opacity: .75; /* standard CSS3 style for transparency */ -moz-opacity: .75; /* transparency for older Mozillas */ filter: alpha(opacity=75); /* transparency for IE; no decimal point */
<div style="position: relative; left: 0px; top: 0px; border: 1px solid black; height: 200px; width: 200px;"> <div style="position: absolute; left: 20px; top: 30px; height: 80px; width: 80px; background-color: red;"></div> <div style="position: absolute; left: 50px; top: 50px; height: 80px; width: 80px; background-color: yellow; opacity: .75; -moz-opacity: .75; filter: alpha(opacity=75);"></div> </div>
style="clip: rect(T R B L)"; style="clip: rect(0px 100px 100px 0px)"; OR style="clip: rect(auto 100px auto auto)"; /*auto matches clipping region to edge of element's box*/
visible | overflow may be drawn ouside elemnt's box |
hidden | overflow is clipped and hidden |
scroll | permanent horizontal and vertical scrollbars. doesn't usually display on printout |
auto | scrollbars if necessary |
function changefont222() { var datext222 = document.getElementById("datext222"); datext222.style.color = "red"; datext222.style.fontWeight = "bold"; datext222.style.border = "2px dashed green"; datext222.style.position = "absolute"; datext222.style.top = "30px"; datext222.style.left = "20px"; } <div style="position: relative; left: 0px; top: 0px; height: 80px; width: 500px; border: 1px solid gray"> <div id=datext222 style="width: 300px; border: 2px solid black;">dis is datext222</div> </div> <form><input type=button value="change datext222" onclick="changefont222(); return(false);"></form>
<div id=containerbox333 style="position: relative; left: 0px; top: 0px; border: 1px solid black; height: 200px; width: 200px;"> <div id=redbox333 style="position: absolute; left: 20px; top: 30px; height: 80px; width: 80px; background-color: red;"></div> <div id=yellowbox333 style="position: absolute; left: 50px; top: 50px; height: 80px; width: 80px; background-color: yellow; opacity: .75; -moz-opacity: .75; filter: alpha(opacity=75);"></div> </div> var dadir333X = 1; var dadir333Y = 2; var dayellowdir333X = -2; var dayellowdir333Y = -1; var tracking333; var containerbox333 = document.getElementById("containerbox333"); var redbox333 = document.getElementById("redbox333"); var yellowbox333 = document.getElementById("yellowbox333"); var damaxX = parseInt(containerbox333.style.width) - parseInt(redbox333.style.width); var damaxY = parseInt(containerbox333.style.height) - parseInt(redbox333.style.height); var damaxYellowX = parseInt(containerbox333.style.width) - parseInt(yellowbox333.style.width); var damaxYellowY = parseInt(containerbox333.style.height) - parseInt(yellowbox333.style.height); function moveboxes333() { var redboxcurX = parseInt(redbox333.style.left); var redboxcurY = parseInt(redbox333.style.top); var yellowboxcurX = parseInt(yellowbox333.style.left); var yellowboxcurY = parseInt(yellowbox333.style.top); if ((redboxcurX >= damaxX) || (redboxcurX <= 0)) { dadir333X = -1 * dadir333X; } if ((redboxcurY >= damaxY) || (redboxcurY <= 0)) { dadir333Y = -1 * dadir333Y; } if ((yellowboxcurX >=damaxYellowX) || (yellowboxcurX <= 0)) { dayellowdir333X = -1 * dayellowdir333X; } if ((yellowboxcurY >=damaxYellowY) || (yellowboxcurY <= 0)) { dayellowdir333Y = -1 * dayellowdir333Y; } var danewX = redboxcurX + dadir333X; var danewY = redboxcurY + dadir333Y; var danewYellowX = yellowboxcurX + dayellowdir333X; var danewYellowY = yellowboxcurY + dayellowdir333Y; var daXtext = danewX + "px"; var daYtext = danewY + "px"; var dayellowXtext = danewYellowX + "px"; var dayellowYtext = danewYellowY + "px"; redbox333.style.left = daXtext; redbox333.style.top = daYtext; yellowbox333.style.left = dayellowXtext; yellowbox333.style.top = dayellowYtext; } function startmove333() { tracking333 = setInterval("moveboxes333()",25); } function stopmove333() { clearInterval(tracking333); } <form><input type=button value="start movement" onclick="startmove333(); return(false);"> <input type=button value="stop movement" onclick="stopmove333(); return(false);"></form>
function getdastyle() { var computingstyleid = document.getElementById("computingstyle"); var typeface = ""; if (computingstyleid.currentStyle) // IE typeface = computingstyleid.currentStyle.fontFamily; else if (window.getComputedStyle) // other browsers typeface = window.getComputedStyle(computingstyleid, null).fontFamily; alert(typeface); } <span id=computingstyle style="border: 1px solid black;"> Test msg</span><br /><br /> <form> <input type=button value="what's the font" onclick="getdastyle(); return(false);"> </form>
var classes = element.className; //can return multiple classes
//assume that class is not already in the classname list element.className += " "; element.className += "aclassname"; OR element.className = "aclassname"; //replace the class name altogether
function enableSS(sheet) { if (sheet == "testcss1") { document.getElementById('testcss1').disabled = false; document.getElementById('testcss2').disabled = true; } else { document.getElementById('testcss1').disabled = true; document.getElementById('testcss2').disabled = false; } } <form> <input type=radio name=choosedastylesheet value=csstest1 checked='checked' onclick="enableSS('testcss1')">csstest1 <input type=radio name=choosedastylesheet value=csstest2 onclick="enableSS('testcss2')">csstest2 </form>
document.styleSheets[] | contains stylesheets |
document.styleSheets[].cssRules[] //W3C document.styleSheets[].rules[] //IE | rules of stylesheets
|
rule.selectorText |
|
rule.style |
|
document.styleSheets[].insertRule() //W3C document.styleSheets[].addRule() //IE | adding style rule
document.styleSheets[0].insertRule("H2 { text-weight: bold; }", 0);
document.styleSheets[0].addRule("H2", "text-weight: bold;", 0); |
document.styleSheets[].deleteTRule() //W3C document.styleSheets[].removeRule() //IE | deleting style rule
document.styleSheets.deleteRule(rulenumfromarray);
document.styleSheets.removeRule(rulenumfromarray); |
//taken from JavaScript: The Definitive Guide (5th edition) by David Flanagan. //Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2 var ss = document.styleSheets[0]; //W3C or IE var rules = ss.cssRules?ss.cssRules:ss.rules; for (var i = 0; i < rules.length; i++) { var rule = rules[i]; //no @import and other nonstyle rules if (!rule.selectorText) continue; var ruleText = rule.selectorText + " { " + rule.style.cssText + " }"; document.write(ruleText + "<br />"); }
Handler | Triggered when | Supported by |
---|---|---|
onabort | Image loading interrupted. | <img> |
onblur | Element loses input focus. | <button>, <input>, <label>, <select>, <textarea>, <body> |
onchange | Selection loses focus, and value has changed since it gained focus. | <input>, <select>, <textarea> |
onclick | mouse press and release; follows mouseup. Return false to cancel default action. | most elements |
ondblclick | double-click | most elements |
onerror | error loading image | <img> |
onfocus | element gains input focus | <button>, <input>, <label>, <select>, <textarea>, <body> |
onkeydown | key pressed down. Return false to cancel. | Form elements and <body> |
onkeypress | key pressed; follows keydown. Return false to cancel. | Form elements and <body> |
onkeyup | key released; follows keypress | Form elements and <body> |
onload | doc load complete | <body>, <frameset>, <img> |
onmousedown | mouse button pressed | most elements |
onmousemove | mouse moved | most elements |
onmouseout | mouse moves off element | most elements |
onmouseover | mouse moves over element | most elements |
onmouseup | mouse button released | most elements |
onreset | form reset requested. Return false to prevent. | <form> |
onresize | window size changes | <body>, <frameset> |
onselect | text selected | <input>, <textarea> |
onsubmit | form submission requested. Return false to prevent. | <form> |
onunload | doc or frameset unloaded. | <body>, <frameset> |
online, offline | browser is online or offline | <navigator> |
hashchange | when content changes | most elements |
transitionend | When a CSS transition ends | most elements |
scroll | when a window starts to scroll | window, textbox, anything w a scrollbar |
<form name="daform500"> <input name="dabutton500" type="button" value="Press Me"> </form> document.daform500.dabutton500.onclick=function() { alert('pressed'); }; function daform500rollover() { document.daform500.dabutton500.value += " please"; } //notice no () document.daform500.dabutton500.onmouseover = daform500rollover;
var dabutton501 = document.daform500.dabutton500; var da500handler = dabutton501.onclick; function da501handler() { alert("first alert"); } dabutton501.onclick = function() { da501handler(); da500handler(); }
eventobject.stopPropagation() | during event propagation, event handler calls this method to stop propagation of event. |
eventobject.preventDefault() | prevents default action (like the click event of an <a> tag. |
element.addEventListener | add the handler to the object. Can add multiple, but no guarantee on order.
object.addEventListener("eventtype",function,true-capturingphase or false-event or bubbling phase)
document.myform.addEventListener("submit",doSomething, false); <div id=dadiv800 style="border: 1px solid gray; width: 200px;">click on me if not IE</div> function doSomething() { alert("hello");
}dadobject = document.getElementById('dadiv800'); if (dadobject.addEventListener) { dadobject.addEventListener("mousedown",doSomething,false);
}click on me if not IE
|
element.removeEventListener() | removes event handler registration |
Event type | Interface | Bubbles | can be cancelled | Supported by/detail properties |
---|---|---|---|---|
abort | Event | yes | no | <img> <object> |
blur | Event | no | no | <a> <area> <button> <input> <label> <select> <textarea> |
change | Event | yes | no | <input> <select> <textarea> |
click | MouseEvent | yes | yes | screenX screenY clientX clientY altKey ctrlKey shiftKey metaKey button detail |
error | Event | yes | no | <body> <frameset> <img> <object> |
focus | Event | no | no | <a> <area> <button> <input> <label> <select> |
load | Event | no | no | <body> <frameset> <iframe> <img> <object> |
mousedown | MouseEvent | yes | yes | screenX screenY clientX clientY altKey ctrlKey shiftKey metaKey button detail |
mousemove | MouseEvent | yes | no | screenX screenY clientX clientY altKey ctrlKey shiftKey metaKey |
mouseout | MouseEvent | yes | yes | screenX screenY clientX clientY altKey ctrlKey shiftKey metaKey relatedTarget |
mouseover | MouseEvent | yes | yes | screenX screenY clientX clientY altKey ctrlKey shiftKey metaKey relatedTarget |
mouseup | MouseEvent | yes | yes | screenX screenY clientX clientY altKey ctrlKey shiftKey metaKey button detail |
reset | Event | yes | no | <form> |
resize | Event | yes | no | <body> <frameset> <iframe> |
scroll | Event | yes | no | <body> |
select | Event | yes | no | <input> <textarea> |
submit | Event | yes | yes | <form> |
unload | Event | no | no | <body> <frameset> |
DOMActivate | UIEvent | yes | yes | detail |
DOMFocusIn | UIEvent | yes | no | none |
DOMFocusOut | UIEvent | yes | no | none |
type | event handler name (with "on" removed (e.g. "click" or "mouseover")) |
srcElement | element on which event occurred |
button | mouse button number pressed (1-left, 2-right, 4-middle) |
clientX, clientY | mouse coordinates at time of event relative to upper-left corner of containing window. |
offsetX, offsetY | position of mouse pointer relative to source element (i.e. where in the img there was a click) |
altKey, ctrlKey, shiftKey | booleans that specify whether Alt, Ctrl, or Shirt keys were held down when event occurred. |
keyCode | Unicode char code of keypress event (keydown or keyup).Use String.fromCharChode() to convert to string. |
fromElement | for mouseover events, this specifies the doc element that the mouse came from |
toElement | for mouseout events, this specifies the doc element that the mouse is going to |
cancelBubble | boolean. Set to true to prevent current event from bubbling further up |
returnValue | boolean. set to false to prevent browser from performing default action associated with event. |
function daEventHandler(event) { if (!event) event = window.event; // get event details for IE //rest of function } //***OR*** function daEventHandler(e) { var event = e || window.event; //rest of function }
document.getElementById("blah801").attachEvent("onmouseover", doSomething); //doSomething is a function defined elsewhere
function addAHandler(form) { form.attachEvent("onsubmit", function() { return validate(); }; }
//won't work with cut and paste text, grab onchange handler <form> <input id="blah6778" type="text" onkeyup="this.value = this.value.toUpperCase();"> </form>
var DataEvent = {}; DataEvent.send = function(target, datatype, data) { if (typeof target == "string") target = document.getElementById(target); if (document.createEvent) { // DOM event model var e = document.createEvent("Events"); e.initEvent("dataavailable", true, false); } else if (document.createEventObject) { // IE event model var e = document.createEventObject(); } else return; // Do nothing in other browsers e.datatype = datatype; e.data = data; if (target.dispatchEvent) target.dispatchEvent(e); // DOM else if (target.fireEvent) target.fireEvent("ondataavailable", e); // IE }; DataEvent.receive = function(target, handler) { if (typeof target == "string") target = document.getElementById(target); if (target.addEventListener) target.addEventListener("dataavailable", handler, false); else if (target.attachEvent) target.attachEvent("ondataavailable", handler); };
document.forms[1].elements[2] OR document.<formname>.<elementname> // Access last form in document document.forms[document.forms.length-1]
<form name=daform onreset="return confirm('Really reset the data?')"> <input type=text name=daaddress value="1 Main Street"> <button type=button onclick="setformvalue();">set the text field value</button> <input type=reset> </form> <script type="text/javascript" language="JavaScript"> function setformvalue() { document.daform.daaddress.value = "set value"; return false; }; </script>
<input type="button"> <button type="button"> | "button" | onclick |
<input type="checkbox"> | "checkbox" | onclick |
<input type="file"> | "file" | onchange |
<input type="hidden"> | "hidden" | |
<option> | ||
<input type="password"> | "password" | onchange |
<input type="radio"> | "radio" | onclick |
<input type="reset"> <button type="reset"> | "reset" | onclick |
<select> | "select-one" | onchange |
<select multiple> | "select-multiple" | onchange |
<input type="submit"> <button type="submit"> | "submit" | onclick |
<input type="text"> | "text" | onchange |
<textarea> | "textarea" | onchange |
<form name=dacheckboxes> <input type=checkbox name=dacheckbox value="first" onclick="checkcheckboxes();">first</input><br /> <input type=checkbox name=dacheckbox value="second" onclick="checkcheckboxes();">second</input><br /> <input type=checkbox name=dacheckbox value="third" onclick="checkcheckboxes();">third</input><br /> </form> <form name=checkingvalues> <input type=text name=valuelisttext value=""> </form> <script type="text/javascript" language="JavaScript"> function checkcheckboxes() { var valuelisttext = ""; for (var i = 0; i < document.dacheckboxes.length; i++) { if (document.dacheckboxes.dacheckbox[i].checked) { valuelisttext = valuelisttext + document.dacheckboxes.dacheckbox[i].value + " "; } } document.checkingvalues.valuelisttext.value = valuelisttext; return false; }; </script>
<form name=blahblah44> <select multiple="multiple" name="daoptions44" size="4"> <option value=one>one</option> </select> <input type=text name=datext44 value=""> <button type=button onclick="addvalue44();">add value</button> <button type=button onclick="deleteselected44();">delete selected values</button> <button type=button onclick="deletevalues44();">delete all values</button> <input type=reset></input> </form> <script type="text/javascript" language="JavaScript"> function deletevalues44() { document.blahblah44.daoptions44.options.length = 0; return false; } function addvalue44() { var dalength = document.blahblah44.daoptions44.options.length; var datext = document.blahblah44.datext44.value; var newoption = new Option(datext, //text property datext, //value property false, //defaultSelected property false); //selected property document.blahblah44.daoptions44.options[dalength] = newoption; return false; } function deleteselected44() { var dalength = document.blahblah44.daoptions44.options.length - 1; for (var i = dalength; i >= 0; i--) { if (document.blahblah44.daoptions44.options[i].selected) { //note that options array will compress towards 0 document.blahblah44.daoptions44.options[i] = null; } } }
<form name=blah55> <button type=button name=clickme55>click me</button> <button type=button onclick="enableclickme55();">enable the click me button</button> </form> <script type="text/javascript" language="JavaScript"> function enableclickme55() { //do this onload to make unobtrusive javascript document.blah55.clickme55.onclick = function() { showclicked55(); } } function showclicked55() { alert("clicked"); } </script>
document.cookie = "version=" + encodeURIComponent(document.lastModified); var nextyear = new Date(); nextyear.setFullYear(nextyear.getFullYear() + 1); function setdacookie77 () { var dastring77 = "version=1" + "; max-age=" + (60*60*24*364); document.cookie = dastring77; // document.cookie = "version=" + document.lastmodified + // "; expires=" + nextyear.toGMTString() + // "; path=/" + // "; domain=jungar.net"; return false; } function cleardacookie77 () { var mydate = new Date(); mydate.setTime(mydate.getTime() - 1); document.cookie = "version=2; max-age=-1"; // document.cookie = "version=2; expires=" + mydate.toGMTString(); // document.cookie = "username=; expires=" + mydate.toGMTString(); // var dastring77 = "version=" + // "; expires=" + mydate.toGMTString(); // "; path=/"; // document.cookie = dastring77; return false; } function showallcookies77 () { var allcookies = document.cookie; var checkcookies = decodeURIComponent(allcookies); alert ("allcookies - " + checkcookies); var dalen = allcookies.length; alert("length = " + dalen); var pos = allcookies.indexOf("version"); if (pos != -1) { alert("we've got a live one"); var start = pos + 8; var end = allcookies.indexOf(";", start); if (end == -1) end = allcookies.length; var value = allcookies.substring(start, end); value = decodeURIComponent(value); alert("value = " + value); } } function cookieenabled77 () { // if (navigator.cookieEnabled != undefined) { // alert("navigator.cookieEnabled - " + navigator.cookieEnabled); // } else { document.cookie = "testcookie=test; max-age=10000"; var cookies = document.cookie; if (cookies.indexOf("testcookie=test") == -1) { alert("testcookie not set"); } else { alert("testcookie set"); } // } }
request.open("GET", url, false, username, password); // store the request // 3rd arg - false=synchronous request/response // 4th & 5th arg for svr that needs auth // 3rd, 4th, and 5th args optional request.setRequestHeader("User-Agent", "XMLHttpRequest"); // set the headers request.setRequestHeader("Accept-Language", "en"); request.setRequestHeader("If-Modified-Since", lastRequestTime.toString()); // Browser will automatically add relevant cookies // unless you add manually request.send(null); // send the request // GET requests, use null // POST requests, send form data
if (request.status == 200 { var datext = request.responseText; // do something with the text } else { alert("Error " + request.status + "L " + request.statusText); } OR if {request.status == 200) { if (request.getResponseHeader("Content-Type") == "text/xml") { var doc = request.responseXML; // Do something with the response document } }
0 | open not called yet |
1 | opened called, but send not called |
2 | send called, server has not responded |
3 | data being received (readyState 3) from server firefox sends this multiple times per large doc IE sends once at beginning of doc download |
4 | response is complete |
var request = HTTP;newRequest(); //from utility function request.onreadystatechange = function() { if (request.readyState == 4) { if (request.status == 200) { var datext = request.responseText; //do something with datext or request.responeText } } } request.open("GET",url); //no 3rd argument - async by default //set headers? request.send(null); // asynch so no block, return immediately
<!-- XML --> <author> <name>Joe Smith</name> <books> <book>Da first title</book> <book>Da second title</book> </books> </author> //JSON { "name": "Joe Smith", "books": [ "Da first title", "Da second title" ] }
<form name=timecompare> Browser time <input type=text name=localtime value=""> Server time <input type=text name=servertime value=""> <button type=button onclick="compareTimes();">Show Times</button> </form>
<script type="text/javascript" language="JavaScript"> function compareTimes() { var d = new Date(); var localdate = d.getDate(); var localmonth = d.getMonth(); var localyear = d.getFullYear(); var localhour = d.getHours(); var localmin = d.getMinutes(); var localsec = d.getSeconds(); if (localmin < 10) { localmin = "0" + localmin; } if (localsec < 10) { localsec = "0" + localsec; } var localdatetime = localmonth + "/" + localdate + "/" + localyear + " " + localhour + ":" + localmin + ":" + localsec; document.timecompare.localtime.value = localdatetime; HTTP.getText("/AJAXDomJavaScript/proutdate.php",putsvrtime); return false; } function putsvrtime(datext) { document.timecompare.servertime.value = datext; } </script>
<?php echo date('n/j/Y G:i:s'); ?>
<form name=xmlview> <textarea name=textversion rows=8 cols=80></textarea> <br /><br /> <u>DOM table<u> <div id=xmlversion class=boxedmono></div> <br /> <u>Character names and descriptions only</u> <div id=characters class=boxedmono></div> <button type=button onclick="grabdaxml();">Grab the XML</button> </form>
function grabdaxml() { HTTP.getXML("/AJAXDomJavaScript/proutxml2.php",putdaxml); return false; } var totaltable = ""; var totaltable2 = ""; function putdaxml(daxml, datext) { document.xmlview.textversion.value = datext; //initialize totaltable totaltable = (put in the table header row for nodeType, nodeName, nodeValue, textContent, Data...) totaltable2 = "<table class=mono>" + "<tr>" + "<th>name</th>" + "<th>desc</th>" + "</tr>"; //grab the dom var n = daxml.documentElement; var children = n.childNodes; var depthstring = "-"; lookforxmltext(children, depthstring); totaltable = totaltable + "</table>" //insert table into the xmlversion div var xmlversion = document.getElementById("xmlversion"); xmlversion.innerHTML = totaltable; //grab the characters nodes only var characternodes = n.getElementsByTagName("character"); lookforcharacters(characternodes); totaltable2 = totaltable2 + "</table>" //insert table into the characters div var xmlversion = document.getElementById("characters"); xmlversion.innerHTML = totaltable2; } function lookforcharacters(characternodelist) { for (var i=0; i < characternodelist.length; i++) { // going to assume that things are in the right order for now // need to check on name because you can get /n and whitespace... if (characternodelist[i].nodeName == "name") { totaltable2 = totaltable2 + "<tr>" + "<td>" + characternodelist[i].textContent + "</td>"; } if (characternodelist[i].nodeName == "desc") { totaltable2 = totaltable2 + "<td>" + characternodelist[i].textContent + "</td>" + "</tr>"; } // in case there's anything deeper if (characternodelist[i].childNodes.length > 0) { lookforcharacters(characternodelist[i].childNodes); } } } function lookforxmltext(Childlist, depthstring) { for (var i=0; i < Childlist.length; i++) { totaltable = totaltable + "<tr>" + "<td>" + depthstring + "</td>" + "<td>" + i + "/" + Childlist.length + "</td>" + "<td>" + Childlist[i].nodeType + "</td>" + "<td>" + Childlist[i].nodeName + "</td>" + "<td>" + Childlist[i].nodeValue + "</td>" + "<td>" + Childlist[i].textContent + "</td>" + "<td>" + Childlist[i].Data + "</td>" + "</tr>"; if (Childlist[i].childNodes.length > 0) { depthstring2 = depthstring + "-"; lookforxmltext(Childlist[i].childNodes, depthstring2); } }
<?php header('Content-type: text/xml'); $xmlstr = <<<XML <?xml version='1.0' standalone='yes'?> (xml for book with title characters, and plot) XML; $xml = new SimpleXMLElement($xmlstr); echo $xml->asXML(); //echo $xml->book[0]->plot; ?>
const scores = [85, 92, 73, 98, 80]; const evenScores = scores.filter(num => num % 2 === 0); // evenScores will be [92, 98, 80]
const sideLengths = [5, 3, 7]; const areas = sideLengths.map(num => num * num); // areas will be [25, 9, 49]
const nestedGroceries = [ ["Apples", ["Red", "Green"]], ["Milk", ["Whole", "2%"]] ]; const flatGroceries = nestedGroceries.flat(); // flatGroceries will be ["Apples", "Red", "Green", "Milk", "Whole", "2%"]
// Original guest list with a duplicate entry const guestList = ["Alice", "Bob", "Charlie", "Alice"]; // Remove duplicates by converting the array to a Set and back to an array const uniqueGuestList = [...new Set(guestList)]; // uniqueGuestList will be ["Alice", "Bob", "Charlie"] console.log(uniqueGuestList);
// Define the age of the user const age = 18; // Determine the message based on the user's age const message = age >= 18 ? "Welcome!" : "Sorry, not yet."; // Output the message console.log(message);
const str = "Hello, world!"; const reversedStr = str.split('').reverse().join(''); // reversedStr will be "!dlrow ,olleH"
const user = { name: "Alice", age: 30 }; // Check if the user object has an 'email' property const hasEmail = "email" in user; // hasEmail will be false because the 'email' property is not present in the user object
const greet = (name = "Guest") => `Hello, ${name}!`; console.log(greet()); // Output: Hello, Guest! console.log(greet("Bob")); // Output: Hello, Bob!
const numbers = [1, 0, null, 3]; // Original array const compactNumbers = numbers.filter(Boolean); // Using filter with Boolean as the callback function // compactNumbers will be [1, 3] because Boolean(1) is true, Boolean(0) is false, Boolean(null) is false, and Boolean(3) is true
const prop = "score"; const person = { [prop]: 90 }; // person will be {score: 90}
let myPromise = new Promise(function(myResolve, myReject) { // "Producing Code" (May take some time) myResolve(); // when successful myReject(); // when error }); // "Consuming Code" (Must wait for a fulfilled Promise) myPromise.then( function(value) { /* code if successful */ }, function(error) { /* code if some error */ } );
function* myGenerator() { yield 1; yield 2; yield 3; } const gen = myGenerator(); console.log(gen.next()); // { value: 1, done: false } console.log(gen.next()); // { value: 2, done: false } console.log(gen.next()); // { value: 3, done: false } console.log(gen.next()); // { value: undefined, done: true }