Categories
JavaScript

JavaScript: Anonymous functions and Inline functions

They don’t have a name, therefore can’t be called. They are usually used as arguments passed to other functions. They enclose a series of tasks to be done, but don’t have a handle to call them directly.

Inline functions are functions passed as arguments to other functions, but instead of passing them as anonymous, we define a name for them:

var myObj = {

myFunction: function(){ // something here; }

myOtherFunction: function nonAnonymous() { // something else here; }

}

nonAnonymous is only visible inside its scope anyways, so it is a as good as the anonymous one, with the difference that it could be referenced recursively from inside nonAnonymous

Categories
JavaScript

Modifying tag attributes with JQuery

  • var imageFile = $(‘#banner img’).attr(‘src’); // To load a javascript variable the ‘src’ part of img tag inside #banner tag
  • var imageFile = $(‘#banner img’).attr(‘src’,’new/path/here’); // To modify the current attribute
  • $(‘body’).removeAttr(‘bgColor’); // To remove an attribute
Categories
JavaScript

Modifying CSS directly with JQuery

  • $(‘#my_tag’).addClass(‘my_class’); // Applies my_class to my_tag (notice we don’t use the dot for the class name
  • $(‘#my_tag’).removeClass(‘my_class’); // The opposite
  • $(‘#my_tag’).toggleClass(‘my_class’); // Adds the class if it wasn’t there, remove it if it was
  • the .css() Jquery function lets you either read the current CSS applied to a tag, or modify it:
    • var bgColor = $(‘#my_tag’).css(‘background-color’); // Reads bg color information into bgColor
    • $(‘#my_tag’).css(‘background-color’,’#FFFFFF’); // Sets the background color of my_tag, you can change multiple CSS properties if you specified the css() argument in between { }
Categories
JavaScript

Jquery innerHTML HTML() function and text and tags manipulation between tags

  • $(‘#errors’).html(‘<p>There are four errors in this form</p>’); // Will put as the content in the div ‘errors’
  • $(‘#errors’).append(‘<p>There are four errors in this form</p>’); // Will append to the content in the div ‘errors’
  • $(‘#errors’).preppend(‘<p>There are four errors in this form</p>’); // Will prepend to the content in the div ‘errors’
  • $(‘#errors’).text(‘<p>There are four errors in this form</p>’); // Will escape HTML tags as HTML entities
  • $(‘#errors’).before(‘<p>There are four errors in this form</p>’); // Will put the code before the specified element.
  • $(‘#errors’).after(‘<p>There are four errors in this form</p>’); // Will put the code after the specified element.
  • $(‘#errors’).remove(); // Will remove the contents of errors
  • $(‘#errors’).replace(‘Brand new content!’); // Will replace the content of errors
Categories
JavaScript

JQuery: selecting elements from the DOM

  • You can select by id: var my_element = $(‘#element_id_here’);
  • You can also select a group of tags: var linksList = $(‘a’);
  • To select elements by class name (and then hide them in this case): $(‘.submenu’).hide();
  • Filter the elements you choose by the preceding ids or tags: $(‘#navBar a’) This will select the a tags that are inside the #navBar id. As a matter of fact, you can follow the CSS syntax to select elements this way. Other variations of this are:
    • $(‘body > p’) – Chooses the p tags that are children of body
    • $(‘h2 + div’) – Chooses the very next adjacent children right after the h2 tag
    • $(‘img[alt]’) – Attribute selecting images (in this case only if they have the alt attribute on them)
    • $(‘input[type=text]’) – Selecting all attributes that have are type=text
    • $(‘a[href^=mailto:]’) & $(‘a[href$=.pdf]’) – Attribute selection using regular expressions
  • Jquery filters: these are used to selectively choose further from a given group of selected items, based on certain criteria:
    • $(‘tr:even’) – From all the list of tr’s, it will only select the ‘even’ elements, you can also use tr:odd as a variation
    • $(‘a:not(.navButton)’); – Select elements that don’t match the criteria inside the not(), in this case select a tags that are not of class navButton
    • $(‘li:has(a)’) – Finds elements that contain another element, in this case, find all the li that contain an ‘a’ tag
    • $(‘a:contains(Click Me!)’) – Find elements that contain a specific piece of text, in this case, find ‘a’ tags that contain the “Click Me!” text inside
    • $(‘div:hidden’).show(); – Find elements that are currently hidden (and in this case show them). This does not find elements with ‘visibility’ property, only takes in account the ‘display’ property. “:visible” will be the opposite of this.
  • Caution about elements picked by Jquery selectors: the normal methods used in JavaScript won’t work, you will have to use the JQuery equivalents. For example:
    • $(‘#banner’).innerHTML = ‘New text’; // won’t work
    • $(‘#banner’).HTML(‘New text’); // Propietary Jquery to say innerHTML, this will work
  • A note about looping through a set of elements selected through Jquery: the loop is already built-in, you don’t have to specify it. For instance:
    • $(‘#slideshow img’).hide(); – The groups of images selected can be hidden without having to loop through them one at a time
  • Chaining functions to an element, you can do this in JQuery, as long as the chain of functions are also JQuery functions as well:
    • $(‘#popUp’).width(300).height(300).text(‘Hi!’).fadeIn(1000);
Categories
JavaScript

JavaScript select an element from a page (or a group of elements)

myelement  = document.getElementById(‘header’);

Where ‘header’ is the id of the tag we are selecting

You can also select a group of elements with:

var pageLinks = document.getElementsByTagName('a');
That will give you an array by the way.
Categories
JavaScript

JavaScript string manipulation

  • Lowercase / Uppercase  
     my_string.toUpperCase() 
     my_string.toLowerCase() 
  • Find first occurrence of substring  
     my_string.indexOf() 
     my_string.lastIndexOf() 
  • Return a portion of your string by indexes  
     string.slice(start, end); 
      Indexes can be negative so you start counting from the end of the string
  • Find index using regular expressions       
     my_regular_expression = /To be/;      
     my_string = “To be or not to be”;      
     sub_str_index = my_string.search(my_regular_expression);      // Finds the first  occurrence index of the reg expr string, or -1 if not found
  • Replacing text       
     date = ‘10.28.2008’;      
     replaceRegEx = /./g;   Looking for a “.” g for globally and not just the first instance    
     date.replace(replaceRegex, ‘/’);   Replace “.” with /
Categories
JavaScript

JavaScript prototype

Objects have “prototypes” from which they may inherit fields and functions.      �
 So you can “customize” or “pre-build” objects with predefined variables and functions on them     �
 Example:     �
  //First, create the custom object “circle”    �
  function circle(){    �
  }    �
  circle.prototype.pi=3.14159    �
  Now all newly spawned instances of circle will have pi predefined, instead of null    �
 Adding methods to a prototype object:     �
  //First, create the custom object “circle”     // create the object method
  function circle(){     function alertmessage(){
  }     alert(this.pi)
  circle.prototype.pi=3.14159     }
       circle.prototype.alertpi=alertmessage

Categories
JavaScript

JavaScript closure

JavaScript function or expression that binds variables internally to their value when the function was spawned.

Useful to limit context for callback function, settimeout loops, or other situations where you want to maintain variables privacy between requests or function callbacks.

Example:

var person = function () {

var name = “Robert”;
return {
getName : function () {
return name;
},
setName : function (newName) {
name = newName;
}
};

}();  //Having parenthesis () runs the function as it is defined

alert(person.name); // Undefined
alert(person.getName()); // Robert
person.setName(“Robert Nyman”);
alert(person.getName()); // “Robert Nyman”

Another example:
function addLinks () {
for (var onclick = function(num){return function(){alert(num)}}, i=0, link; i<5; i++) {
link = document.createElement(”a”);
link.innerHTML = “Link ” + i;     Append links that onclick will produce an alert with the original ‘I’ variable assigned to it
link.onclick = onclick(i);
document.body.appendChild(link);
}
};
onload = addLinks;

Another example:

function callLater(paramA, paramB, paramC){ /* Return a reference to an anonymous inner function created with a function expression:- */

return (function(){ /* This inner function is to be executed with – setTimeout – and when it is executed it can read, and act upon, the parameters passed to the outer function:- */

paramA[paramB] = paramC; });

} … /* Call the function that will return a reference to the inner function object created in its execution context. Passing the parameters that the inner function will use when it is eventually executed as arguments to the outer function. The returned reference to the inner function object is assigned to a local variable:- */

var functRef = callLater(elStyle, “display”, “none”); /* Call the setTimeout function, passing the reference to the inner function assigned to the – functRef – variable as the first argument:- */

hideMenu=setTimeout(functRef, 500);

keyword: closures

Categories
JavaScript

Ajax

  • asynchronous javascript and xml
  • Disadvantages:
    • Depends on JS to be turned on
    • Difficult to maintain a clear separation between presentation and logic layers, may be difficult to debug
    • Search engines will not be able to access ajax based data
  • The five status of ajax return call code: 5 readyStates0 = uninitialized1 = loading2 = loaded3 = interactive4 = complete
  • Ajax polling methods:
    • HTTP pull: Client constantly and periodically ping the server for data
    • COMET / Bauyer approach: the server side runs in a self loop for a given period of time (usually 45 secs), if any new event occurs in that time, it is sent to the client. If not, the client at the end reopens another 45 secs loop.