Javascript

From Alessandro's Wiki
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Image Preload

  • Tratto da i templates di Quanta Plus
/* To include this script into an xhtml page without copying and pasting it in 
add the following tags into your xhtml page. Please note that these comments are 
only valid within .js (JavaScript files), 
do not include them if you wish to use this script within an xhtml document.
<script type="text/javascript" src="./preload.js"></script> 
Or copy and paste the script into your document head enclosed in 
<script type="text/javascript"></script> tags */
var arImages=new Array();
function Preload() {
 var temp = Preload.arguments; 
 for(x=0; x < temp.length; x++) {
  arImages[x]=new Image();
  arImages[x].src=Preload.arguments[x];
 }
}
/*this replaces your normal 'body' tag
substitute your own image names*/
/*
< body onload="Preload('thing.png','anotherthing.png','etc etc.png')" >
*/

AJAX Call

  • Create the object
if (window.XMLHttpRequest ){   var XmlHttp = new XMLHttpRequest();                     }
else {                         var XmlHttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");  }
  • Create the Reequest:
if ( ! XmlHttp ) {
  XmlHttp = new XMLHttpRequest();
}
else {
  XmlHttp.abort();         
}
  • Get the url fetched:
XmlHttp.open("get", PageUrl , true);
XmlHttp.onreadystatechange = function () {
  if (XmlHttp.readyState == 4) {
     if (XmlHttp.status == 200) {
  • if everything goes well, put the result in a div called (with id) "divContent".
         document.GetElementById( "divContent" ).innerHTML = XmlHttp.responseText;
     } else
  }      alert( "error : " + PageUrl );
};
XmlHttp.send( null );

Create element "on the fly"

var but = document.createElement( "INPUT" );
    but.setAttribute( 'type'  ,  'submit' );
    but.setAttribute( 'value' ,  'upload' );

Syntax

Switch

switch( action ) {
 case "stock":
 /* code code code */
 break;
 default:
 /* code code code */
 break;
}

Strings

  • Concatenating:
var BigString = StringFirst + " words between strings " + StringLast ;

popup window

<input type="button" value="open in new window" onclick="window.open('http://www.ciao.com')">


Null

from: http://lists.evolt.org/archive/Week-of-Mon-20050214/169524.html

  "
    Well, first of all, in JavaScript null is an object. There’s another
    value for things that don’t exist, undefined. The DOM returns null for
    almost all cases where it fails to find some structure in the
    document, but in JavaScript itself undefined is the value used.

    Second, no, they are not directly equivalent.
    If you really want to check for null, do:

    if (null == yourvar) // with casting
    if (null === yourvar) // without casting

    If you want to check if a variable exist

    if (typeof yourvar != ‘undefined’) // Any scope
    if (window['varname'] != undefined) // Global scope
    if (window['varname'] != void 0) // Old browsers

    If you know the variable exists but don’t know if there’s any value
    stored in it:

    if (undefined != yourvar)
    if (void 0 != yourvar) // for older browsers

    If you want to know if a member exists independent of whether it has
    been assigned a value or not:

    if (‘membername’ in object) // With inheritance
    if (object.hasOwnProperty(‘membername’)) // Without inheritance

    If you want to to know whether a variable autocasts to true:

    if(variablename)
  "

facebook

  • select all friends / invite all friends
javascript:fs.select_all();


jQuery

$(this)	Current HTML element
$("p")	All <p> elements
$("p.intro")	All <p> elements with class="intro"
$("p#intro")	All <p> elements with id="intro"
$("p#intro:first")	The first <p> element with id="intro"
$(".intro")	All elements with class="intro"
$("#intro")	The first element with id="intro"
$("ul li:first")	The first <li> element of the first <ul>
$("[href$='.jpg']")	All elements with an href attribute that ends with ".jpg"
$("div#intro .head")	All elements with class="head" inside a <div> element with id="intro"

event methods

$(document).ready(function)  	Binds a function to the ready event of a document
(when the document is finished loading)
$(selector).click(function)	Triggers, or binds a function to the click event of selected elements
$(selector).dblclick(function)	Triggers, or binds a function to the double click event of selected elements
$(selector).focus(function)	Triggers, or binds a function to the focus event of selected elements
$(selector).mouseover(function)	Triggers, or binds a function to the mouseover event of selected elements

effects methods

$(selector).slideDown(speed,callback)
$(selector).slideUp(speed,callback)
$(selector).slideToggle(speed,callback)

$(selector).fadeIn(speed,callback)
$(selector).fadeOut(speed,callback)
$(selector).fadeTo(speed,opacity,callback)

animate({width:"70%",opacity:0.4,marginLeft:"0.6in",fontSize:"3em"});
$(document).ready(function(){
  $("button").click(function(){
    $("div").animate({height:300},"slow");
    $("div").animate({width:300},"slow");
    $("div").animate({height:100},"slow");
    $("div").animate({width:100},"slow");
  });
});
$(selector).hide()	Hide selected elements
$(selector).show()	Show selected elements
$(selector).toggle()	Toggle (between hide and show) selected elements
$(selector).slideDown()	Slide-down (show) selected elements
$(selector).slideUp()	Slide-up (hide) selected elements
$(selector).slideToggle()	Toggle slide-up and slide-down of selected elements
$(selector).fadeIn()	Fade in selected elements
$(selector).fadeOut()	Fade out selected elements
$(selector).fadeTo()	Fade out selected elements to a given opacity
$(selector).animate()	Run a custom animation on selected elements

css interaction

$("p").css("background-color","yellow");


method list

  • events

http://www.w3schools.com/jquery/jquery_ref_events.asp

  • animation effects.

http://www.w3schools.com/jquery/jquery_ref_effects.asp

animate()	Performs a custom animation (of a set of CSS properties) for selected elements
clearQueue()	Removes all queued functions for the selected element
delay()	Sets a delay for all queued functions for the selected element
dequeue()	Runs the next queued functions for the selected element
fadeIn()	Gradually changes the opacity, for selected elements, from hidden to visible
fadeOut()	Gradually changes the opacity, for selected elements, from visible to hidden
fadeTo()	Gradually changes the opacity, for selected elements, to a specified opacity
fadeToggle()	 
hide()	Hides selected elements
queue()	Shows the queued functions for the selected element
show()	Shows hidden selected elements
slideDown()	Gradually changes the height, for selected elements, from hidden to visible
slideToggle()	Toggles between slideUp() and slideDown() for selected elements
slideUp()	Gradually changes the height, for selected elements, from visible to hidden
stop()	Stops a running animation on selected elements
toggle()	Toggles between hide() and show(), or custom functions, for selected elements
  • html methods

http://www.w3schools.com/jquery/jquery_ref_html.asp

addClass()	Adds one or more classes (for CSS) to selected elements
after()	Inserts content after selected elements
append()	Inserts content at the end of (but still inside) selected elements
appendTo()	Inserts content at the end of (but still inside) selected elements
attr()	Sets or returns an attribute and value of selected elements
before()	Inserts content before selected elements
clone()	Makes a copy of selected elements
detach()	Removes (but keeps a copy of) selected elements
empty()	Removes all child elements and content from selected elements
hasClass()	Checks if any of the selected elements have a specified class (for CSS)
html()	Sets or returns the content of selected elements
insertAfter()	Inserts HTML markup or elements after selected elements
insertBefore()	Inserts HTML markup or elements before selected elements
prepend()	Inserts content at the beginning of (but still inside) selected elements
prependTo()	Inserts content at the beginning of (but still inside) selected elements
remove()	Removes selected elements
removeAttr()	Removes an attribute from selected elements
removeClass()	Removes one or more classes (for CSS) from selected elements
replaceAll()	Replaces selected elements with new content
replaceWith()	Replaces selected elements with new content
text()	Sets or returns the text content of selected elements
toggleClass()	Toggles between adding/removing one or more classes (for CSS) from selected elements
unwrap()	Removes the parent element of the selected elements
val()	Sets or returns the value attribute of the selected elements (form elements)
wrap()	Wraps specified HTML element(s) around each selected element
wrapAll()	Wraps specified HTML element(s) around all selected elements
wrapInner()	Wraps specified HTML element(s) around the content of each selected element
  • CSS properties.

http://www.w3schools.com/jquery/jquery_ref_css.asp

addClass()	Adds one or more classes to selected elements
css()	Sets or returns one or more style properties for selected elements
hasClass()	Checks if any of the selected elements have a specified class
height()	Sets or returns the height of selected elements
offset()	Sets or returns the position (relative to the document) for selected elements
offsetParent()	Returns the first parent element that is positioned
position()	Returns the position (relative to the parent element) of the first selected element
removeClass()	Removes one or more classes from selected elements
scrollLeft()	Sets or returns the horizontal position of the scrollbar for the selected elements
scrollTop()	Sets or returns the vertical position of the scrollbar for the selected elements
toggleClass()	Toggles between adding/removing one or more classes from selected elements
width()	Sets or returns the width of selected elements
  • AJAX methods:

http://www.w3schools.com/jquery/jquery_ref_ajax.asp

$.ajax()	Performs an AJAX request
ajaxComplete()	Specifies a function to run when the AJAX request completes
ajaxError()	Specifies a function to run when the AJAX request completes with an error
ajaxSend()	Specifies a function to run before the AJAX request is sent
$.ajaxSetup()	Sets the default values for future AJAX requests
ajaxStart()	Specifies a function to run when the first AJAX request begins
ajaxStop()	Specifies a function to run when all AJAX requests have completed
ajaxSuccess()	Specifies a function to run an AJAX request completes successfully
$.get()	Loads data from a server using an AJAX HTTP GET request
$.getJSON()	Loads JSON-encoded data from a server using a HTTP GET request
$.getScript()	Loads (and executes) a JavaScript from the a server using an AJAX HTTP GET request
load()	Loads data from a server and puts the returned HTML into the selected element
$.param()	Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests)
$.post()	Loads data from a server using an AJAX HTTP POST request
serialize()	Encodes a set of form elements as a string for submission
serializeArray()	Encodes a set of form elements as an array of names and values
  • Misc Methods

http://www.w3schools.com/jquery/jquery_ref_misc.asp

Method	Description
data()	Attaches data to, or gets data from, selected elements
each()	Run a function for each element matched by the jQuery selector
get()	Get the DOM elements matched by the selector
index()	Search for a given element from among the matched elements
$.noConflict()	Release jQuery s control of the $ variable
$.param()	Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests)
removeData()	Removes a previously-stored piece of data
size()	Return the number of DOM elements matched by the jQuery selector
toArray()	Retrieve all the DOM elements contained in the jQuery set, as an array