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

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

Jquery toggle function

This function respond to click events in an element, calling the functions specified as you click or toggle actions on it:

function showSubmenu() {
  $('#submenu').show();
}
function hideSubmenu() {
  $('#submenu').hide();
}
$('#menu').toggle(showSubmenu, hideSubmenu);
Categories
JavaScript

JQuery onhover function

Example:

function showSubmenu() {
  $('#submenu').show();
}
function hideSubmenu() {
  $('#submenu').hide();
}
$('#menu').hover(showSubmenu, hideSubmenu);
You can also use anonymous functions inside the hover()
Categories
JavaScript

Jquery onload event

Example:

$(document).ready(function() {
  //your code goes here
});

Categories
JavaScript

Javascript event types, and JQuery event handling

Even if multiple events are happening in the DOM, only one is being handle at a time, everything else is put in hold in the mean time, even thing running under setTimeOut for example. This is because javascript is single threaded.

  • Inline events: events embeded in the HTML of the page (see example below), not recommended because you are mixing HTML and JavaScript functionality, and you can only attach one event per DOM element:
<a href="page.html" onmouseover="alert('this is a link');">A link</a>
  • The traditional way: directly assign a function name to a page element (see example below). Note that you can’t use () in the function call, otherwise JavaScript will run the function right away, not at event time. Another disadvantage is that you can only assign one function to one event handler at a time. For instance, window.onload=[my event] where “my event” can only be one function, if specified again, it would overwrite the previous call.
function message() {
  alert("Welcome...");
}
window.onload=message;
  • Event listeners: Same concept as above, but you can assign multiple event listeners per element. The problem here is that IE has its own, propietary way of doing this. All other browsers (Firefox, Safari) use addEventListener(), IE uses attachEvent() for this purpose. removeEventListener and removeEvent are also used to remove events from DOM elements. It is recommended to use a JavaScript library to mask these differences.
  • Here are some of the ways JQuery handle events:
    • $(‘a’).mouseover( ); // Adds a mouseover event to all links in the page
    • $(‘#start’).click(startSlideShow); // Calls function startSlideShow when #start element is clicked
    • $(‘#menu’).mouseover(function() {
      $(‘#submenu’).show();
      }); // Pass an anonymous function to the event handler
Categories
JavaScript

each() function on JQuery

Use it to pass an anonymous function that will perform specific tasks on the element at hand. Example:

$('a[href^=http://]').each(function() {
  var extLink = $(this).attr('href');
  $('#bibList').append('<li>' + extLink + '</li>');
});
For all the links that do have an 'http://...' link, load extLink with the href of each one of them, and then append a list bullet with it.
Note how $(this) encapsules the argument element passed to the anonymous function.
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