Categories
JavaScript

Javascript: Closures / object / function in javascript

Functions are first-class objects, i.e. they are objects and can be manipulated and passed around like just like any other object. Specifically, they are Function objects.

A closure is an expression (typically an inner function) that can have free variables together with an environment that binds those variables (that “closes” the expression).

Inner functions have access to the variables of their enclosing outer function, but after running the outer function, you can’t have access to modify their inner scope, just to use it.

Be careful with closures: they could occupy memory without the possibility of being clear out until next page reload.

Categories
JavaScript

JavaScript Augmentation of types

Say we want to add methods to a certain type. For example, adding a trim function to the String type:

String.method(‘trim’, function (  ) {
    return this.replace(/^s+|s+$/g, ”);
});

document.writeln(‘”‘ + ”   neat   “.trim(  ) + ‘”‘);

Categories
JavaScript

Javascript Performance and best practices

The following tips can be used to improve sluggish javascript code:

  • Avoid using the eval() function.
  • Avoid the with construction.
  • Minimize repetitive expression evaluation.
  • Use simulated hash tables for lookups in large arrays of objects.
  • Avoid excessive string concatenation.
  • Investigate download performance.
  • Avoid multiple document.write() method calls.
  • Use global namespace variables to encapsulate your variables, to avoid colisions with other JavaScripts
  • Recursion, as elegant as it is, is heavy in js, and it takes longer to execute than regular for or while loops. It can produce stack overflows. Use it lightly.

Source (for more details on why): http://www.devarticles.com/c/a/JavaScript/More-on-Variables-Functions-and-Flow-Control/3/

To check your JavaScript code for best practices you can use jlint:

http://www.jslint.com/

More lessons learned in the trenches:

  • When you user JS to switch classes, the DOM has to redraw and recalculate all the CSS associated with that and the children tags. Try to do it lightly, or try to stick to switching styles as inline inserts, Jquery animations style
  • When you need to use setTimeOut, use requestAnimationFrame instead. In a nutshell, it is a way for browsers to give you access to the frames when they refresh stuff, so your updates to the UI will be coordinated with other animations and things going on the UI. Here is an easy to digest example of this usage (or more complicated at the original source https://gist.github.com/1579671 ):
 window.requestAnimFrame = (function(){
      return  window.requestAnimationFrame       || 
              window.webkitRequestAnimationFrame || 
              window.mozRequestAnimationFrame    || 
              window.oRequestAnimationFrame      || 
              window.msRequestAnimationFrame     || 
              function( callback ){
                window.setTimeout(callback, 1000 / 60);
              };
    })();
Categories
JavaScript

JavaScript error messages, error handling and try catch

To avoid errors being presented to the end user:

function doNothing() {return true;}
 window.onerror = doNothing;

But of course, the best way to handle this (after IE 5), is by using try{ } catch { } structures:

<script type=”text/javascript” language=”JavaScript1.5″>
  function myFunc() {
      try {
          // statement(s) that could throw an error if various conditions aren’t right
      }
      catch(e) {
          // statements that handle the exception (error object passed to e variable)
      }
  }
  </script>

Note how the script has to be set as javascript1.5 to avoid old browsers to run into problems with try catch.

The following table indicates what’s available from the “e” error object passed to the catch statement, and what browsers support it:

Property IE/Windows Mozilla Safari Opera Description      
description 5 n/a n/a n/a Plain-language description of error  
fileName n/a all n/a n/a URI of the file containing the script throwing the error 
lineNumber n/a all n/a n/a Source code line number of error  
message 5.5 all all 7 Plain-language description of error (ECMA)  
name 5.5 all all 7 Error type (ECMA)      
number 5 n/a n/a n/a Microsoft proprietary error number  
stack n/a 1.0.1 n/a n/a Multi-line string of function references leading to error
 From inside a try statement, you can throw errors yourself:
throw err;
Categories
JavaScript

JQuery and Ajax

$('#headlines').load('todays_news.html'); // Loads the html page into the headlines DOM element

The limitation of the method above is that  the page loaded has to be from the same server / domain.

If you want to load only an specific part of the requested page, you can access only that part by id (say id is ‘news’):

$('#headlines').load('todays_news.html #news');

In JQuery, the way to specify GET and POST commands is as follows:

$.get(url, data, callback);  // or  $.get(‘rateMovie.php’,’rating=5′);

$.post(url, data, callback); // or $.post('rateMovie.php','rating=5&user=Bob');

Just remember that when preparing the data,  you have to url encode some of the arguments:

encodeURIComponent(‘Mac & Cheese’);

If you want to include all the elements of a form at once when you send your request, you can use the serialize() function to do so (say your form id is #login):

var formData = $('#login').serialize();
$.get('login.php',formData,loginResults);

This is a typical callback function:

function processResponse(data, status) {
     var newHTML;
     if (status==’success’) {
       newHTML = ‘<h2>Your vote is counted</h2>’;
       newHTML += ‘<p>The average rating for this movie is ‘;
       newHTML += data + ‘.</p>’;
     } else {
       newHTML='<h2>There has been an error.</h2>’;
       newHTML+='<p>Please try again later.</p>’;
     }
     $(‘#message’).html(newHTML);
   }

The callback function could also be specified as an anonymous function:

.get('file.php', data, function(data,status) {
   // callback function programming goes here
});

If you received XML content back from the server, you can parse it this way:

$.get(‘xml.php’,’id=234′,processXML);
function processXML(data) {
  var messageContent=$(data).find(‘content’).text();
}

In this example, the actual XML received may look like:

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<message id=”234″>
  <from>Bob</from>
  <to>Janette</to>
  <subject>Hi Janette</subject>
  <content>Janette, let’s grab lunch today.</content>
</message>

In order to convert the response to a JSON object usable by JavaScript directly, you can use the following:

$.getJSON(‘contacts.php’,’contact=123′,processContacts); // same as $.get(), but the ‘data’ variable is a JSON object instead of text

If you need to loop through a JSON object, you can use the JQuery $.each() function.

Say that you have the following object coming back from the server:

var data = {
  contact1: {
    firstName: 'Frank',
    lastName: 'Smith',
    phone: '503-555-1212'
  },
  contact2: {
    firstName: 'Peggy',
    lastName: 'Jones',
    phone: '415-555-5235'
  }
};

The following callback function can be used to parse it:

   $.getJSON(‘contacts.php’,’limit=2′,processContacts);
   function processContacts(data) {
     // create variable with empty string
     var infoHTML=”;

     //loop through each object in the JSON data
     $.each(data,function(contact, contactInfo) {
         infoHTML+='<p>Contact: ‘ + contactInfo.firstName;
         infoHTML+=’ ‘ + contactInfo.lastName + ‘<br>’;
         infoHTML+=’Phone: ‘ + contactInfo.phone + ‘</p>’;
     }); // end of each()

     // add finished HTML to page
     $(‘#info’).html(infoHTML);
   }

In that case, the argument ‘contact’ will point to ‘contact1’ and ‘contact2’, and the contactInfo to the information on each of those sub-objects

Categories
JavaScript

Ajax

XMLHttpRequest object: is a browser object that allows you to communicate to the server. To create one of these objects you use the following JavaScript code:

var newXHR = new XMLHttpRequest(); // Doesn’t work in IE 6 though

In order to send a GET request using the object above, you do something like:

newXHR.open(‘GET’, ‘shop.php?productID=34’);

To indicate the callback function that will process the request received back from the server:

newXHR.onreadystatechange = myCallbackFunction;

Up to this point, everything has been setup, now to send the data to the server you use:

newXHR.send(null);

If you want to send additional parameters, instead of null you specify:

newXHR.send('q=javascript');

The XHR object receives up to three pieces of information back from the server:

  • status: like 404, 500, 200, etc
  • responseText property: it is part of the XHR object, and stores the server response, could be HTML, plain text, or a JSON object
  • responseXML property: also part of the XHR object. Loaded if the server responds with XML
Categories
JavaScript

Forms manipulation in JQuery

var fieldValue = $(‘#user’).val(); // Get the value of the form field with id ‘user’

var fieldValue = $(‘#user’).val(‘Value to set’); // Set the value of the form field with id ‘user’

var fields = document.getElementsByTagName(‘input’); // Select all form fields

$(‘:input’).attr(‘disabled’,true); // Disable input fields

To select all form fields of a given type in JQuery:

$(‘:input’) Selects all input, textarea, select, and button elements. In other words, it selects all form elements.
$(‘:text’) Selects all text fields.
$(‘:password’) Selects all password fields.
$(‘:radio’) Selects all radio buttons.
$(‘:checkbox’) Selects all checkboxes.
$(‘:submit’) Selects all submit buttons.
$(‘:image’) Selects all image buttons.
$(‘:reset’) Selects all reset buttons.
$(‘:button’) Selects all fields with type button.
$(‘:file’) Selects all file fields (used for uploading a file).
$(‘:hidden’) Selects all hidden fields.

You can combine form selectors as follows: $(‘#signup :text’) // Select ‘signup’ element but only text input fields from those selected

$(‘:checked’) Select all checkboxes that have been checked

if ($('#news').attr('checked')) {
  // the box is checked
} else {
  // the box is not checked
}
var selectedState=$('#state :selected').val(); // Gets the value of the selected fields of 'states'
Example of submit event:
$(document).ready(function() {
      $('#signup').submit(function() {
         if ($('#username').val() == '') {
            alert('Please supply a name in the Name field.');
            return false;
         }
      }); // end submit()
}); // end ready()
Example of focus event:
$('#username').focus(function() {
     var field = $(this);
     if (field.val()==field.attr('defaultValue')) {
       field.val('');
     }});
Example of change event:
$('#country').change(function() {
  if ($(this).val()=='Please choose a country') {
    alert('Please select a country from this menu.');
  }
}
Categories
JavaScript

popup windows created with JavaScript

var winProps = ‘width=400,height=300,location=yes’;
var newWin = open(‘about.html’,’aWin’,winProps);

newWin.close();

  • height dictates the height of the window, in pixels. You can’t specify percentage values or any other measurement besides pixels. If you don’t specify a height, the Web browser matches the height of the current window.
  • width specifies the width of the window. As with height, you can only use pixels, and if you leave this property out, the Web browser matches the width of the current window.
  • left is the position, in pixels, from the left edge of the monitor.
  • top is the position, in pixels, from the top edge of the monitor.
  • resizable specifies whether a visitor can resize the window by dragging.
  • scrollbars appear at the right and bottom edges of a browser window whenever a page is larger than the window itself. To completely hide the scrollbar, set this property to no. You can’t control which scrollbar is hidden (it’s either both or neither).
  • status controls the appearance of the status bar at the bottom of the window. Firefox and Internet Explorer normally don’t let you hide the status bar, so it’s always visible in those browsers.
  • toolbar sets the visibility of the toolbar containing the navigation buttons, bookmark button, and other controls available to the particular browser. On Safari, the toolbar and location settings are the same: turning on either one displays both the toolbar buttons and the location field.
  • location specifies whether the location field is visible. Also known as the address bar, this field displays the pages URL and lets visitors go to another page by typing a new URL. Opera, IE 7, and Firefox don’t let you hide a page’s location entirely. If you don’t turn on the location property, then the page’s URL appears up in the title bar. This feature is supposed to stop nefarious uses of JavaScript like opening a new window and sending you off to another site that looks like the site you just left. Also, Safari displays the toolbars as well as the location field with this property turned on.
  • menubar applies to browsers that have a menu at the top of their windows (for example, the common File and Edit menus that appear on most programs). This setting applies only to Windows browsers—Macs have the menu at the top of the screen, not the individual window. And it doesn’t apply to IE 7, which doesn’t normally display a menu bar.
Categories
HTML Templates JavaScript JavaScript Effects Index

Index of JavaScript effects and HTML Templates

NOTE: For the actual files (since wordpress is failing to upload) see http://onsubject.com/localhost
  1. lightbox: (uunet.zip in localhost)
  2. cycle (several slide show animations, shuffle, fade, etc): http://localhost/uunet/index.php?action=buy
  3. Simple text horizontal menus (floated and in-line versions): http://localhost/html_template/horizontal_menu.html
  4. Belated, pure CSS buttons: http://localhost/html_template/belated_css_buttons.html
  5. Fish dynamic horizontal menu with sub-menu options: http://localhost/html_template/fish_dynamic_menu/
  6. JQuery date picker: http://localhost/html_template/datepicker/ The actual css / images / support files can be downloaded from: http://jqueryui.com/download
  7. JQuery form validation: http://localhost/html_template/form_validation/
  8. JQuery accordion: http://localhost/html_template/accordion/
  9. JQuery tabs: http://localhost/html_template/tabs/
  10. JQuery tooltips: http://localhost/html_template/tooltip/
  11. JQuery sortable table: http://localhost/html_template/table_sorter/
  12. Rounded corners bubble: http://localhost/css_tutorial/rounded%20corners/ another example of this is on: http://localhost/jobs/hgm/hgm_exercise.html
Categories
JavaScript

JavaScript events and the bind() function

The format is: 

$('#selector').bind('click', myData, functionName);
The first argument (in this case click) is the event attached to the element.
The second argument is a data structure, to pass more data to the handling function.
The third argument is the handing function itself. It can be an anonymous function.
Example of usage:
var linkVar = { message:'Hello from a link'};
var pVar = { message:'Hello from a paragraph};
function showMessage(evt) {
    alert(evt.data.message);
}
$('a').bind('click',linkVar,showMessage);
$('p').bind('mouseover',pVar,showMessage);