JDev

javascriptJuly 23, 2008 12:14 pm

A good explanation of the JavaScript event delegation can found in this SitePoint article.

 

Code, javascript, .NETJune 25, 2008 1:36 pm

When you use href=’#’ and provide a JavaScript function for the onclick event, the browser always jumps to the top of the page after executing the JavaScript function. The simple way to avoid the jumping effect is to include a ‘return false’ statement after the call to the JavaScript function. Example:

<a href=’#’ onclick=’fnClick(this); return false;’>Do something </a> 

If you use .NET 1.1, you can set "Smartnavigation=true" in Document properties.

Code, javascriptJune 13, 2008 1:39 pm

I used a NiftyCube javascript and css from Alessandro Fulciniti to create rounded corners for a form. The form used fieldset and legend tags to separate different sections of the form. I used ‘border-style:none‘ for the fieldset to get rid of the borders around it. The NiftyCube worked perfectly in Internet Exporer, however the form looked messy in Firefox. The rounded corners were below the legend.

The solution was to get rid of the legend tag and use a div tag within the fieldset with the following style:

    display:block;
    margin:10px;
    font-weight:bold; 

Form with rounded corners 

Code, javascript, jqueryMay 1, 2008 5:12 pm

$(’div.panel’)
    All divs with class=“panel”
 $(’p#intro’)
    The paragraph with id=“intro”
 $(’div#content a:visible’)
    All visible links inside the div with id=“content”
 $(’input[@name=email]’)
    All input fields with name=“email”
$(’input[id*=plan]’)
    All input fields whose id contains string ‘plan’
 $("table.striped > tr:odd")
     Odd rows in a table with a striped class
 $(’a[@href^="http://"]’)
    All external links (links that start with http://)
 $(’p[a]’)
    All paragraphs that contain one or more links     
    
 $("p:even");
    All even <p> elements.
 $("tr:nth-child(1)");
  The first row of each table.
 $("body > div");
   Direct <div> children of <body>.
 $("a[href$=pdf]");
    Links to PDF files.
 $("body > div:has(a)")
   Direct <div> children of <body>-containing links.

 $("td:empty)")
    Empty table cells 

 
$(’#plugins td.name’).filter(’:contains(ImageManager)’)
    In the <div id=plugins>, find <td class=name> which contains the text ImageManager
 

More on Jquery. 

 

Code, javascript, prototypeApril 17, 2008 7:05 pm

Here is how you could do a text-based slideshow in Prototype/Script.aculo.us:

We declare a JavaScript array:

var students = new Array ("Audrey", "John", "Mark", "Benny", "Peter");  

We need a div with an id of ‘panel’ that will contain the slideshow.

document.observe(’dom:loaded’ , function() {
     i=0;
     new PeriodicalExecuter(cycle, 5  //5-second interval
     );
 });
 
function cycle(){                          
         $(’panel’ ).visualEffect  (’BlindUp’,
              { duration: 1,             
              fps: 50,           
            afterFinish: function() {           
            $(’panel’).update(students[i]); //the div is still invisible at this point
            $(’panel’ ).visualEffect  (’BlindDown’,
              { duration: 1,
                fps: 50,
                queue:’end’
              }
            );        
         }
       });
        
        i++;
        if(i==students.length)
             i=0; //restart the slideshow
 }

 

This code will display all the elements of the array, one by one, automatically at a 5-second  interval.

Code, javascript, prototypeApril 10, 2008 8:37 pm

An excellent explanation can be found here.

Code, javascript, prototype, jqueryFebruary 26, 2008 3:47 pm

We are going to show how to create lists with alternate colors in Prototype and Jquery.

Let’s say you have an HTML list with with the ‘result‘ id, and you want it to have alternating colors. 

First, create a css class that displays a list item in a different color:

li.alternate { color:green;} 

In Prototype, you use the following syntax:

document.observe(’dom:loaded’ , function(){
    $$(’#result li:nth-child(2n)’ ).invoke(’addClassName’ , ‘alternate’ );
});

Jquery uses the following syntax:

$(document).ready(function(){       
    $("#result li:nth-child(even)").addClass("alternate");           
});

Code, javascriptJanuary 29, 2008 9:06 pm

Let’s say you have two text-boxes that show dates, and you need to get a difference between the two. There  is no built-in JavaScript function to calculate the difference but you can easily accomplish it using a few JavaScript functions.

Let’s assume that a date is represented in the following format: mm/dd/yyyy.

First we need to convert this string into a JavaScript Date object. Here is a function that does that.

function convertToDate(str){

    var arr = str.split(’/');
    var year = arr[2];
    var day = arr[1];
    var month = arr[0]-1; //month argument starts with 0

    return new Date(year, month, day, 0,0,0);
}

Pass a string to the function and get a Date object back. You may need to modify it depending on your date format and separator used. 

 Now we can get 2 strings from text-box values that have the following ids : startDate and endDate, and convert them to Date objects.

    var start =  document.getElementById ("startDate");
    var end =  document.getElementById ("endDate");
       
    var d1 = convertToDate(start.value);
    var d2 = convertToDate(end.value);

The following statement calculates the difference between 2 Date objects in milliseconds: 

    var span = d2.getTime()- d1.getTime();

Let’s calculate the number of milliseconds in a day:
  
    var day = 1000*60*60*24;

And finally, the representation of the difference in days:

    var days = parseInt(span/day);

Code, dom, javascriptDecember 4, 2007 3:27 pm

Did you know that you can use any custom attributes for your HTML tags? For example:

<div id=’myDiv’ firstName=’John’></div>

 Now, in your JavaScript code, you get the value of your custom attribute as follows:

var div = document.getElementById (’myDiv’);
var fName = div.getAttribute(’
firstName‘); 

This technique may prove useful if you manipulate and re-arrange HTML elements on your web page. 

 

Code, javascriptNovember 19, 2007 8:31 pm

Here is a little function that returns an array of all text fields in a document:

function getAllTextFields(){   

    var texts = [];
    var inputs =      document.getElementsByTagName(’input’);

    for(var i=0; i <inputs.length; i++)
            if(inputs[i].type == ‘text’)
                texts.push(inputs[i]);

     return texts;

Code, javascript, ajaxJuly 17, 2007 6:42 pm

Let’s say you want to bring down a list of names from the server and display them without reloading the page.

I’ll show you a simple way to do it using the Ajax technology.

1. Create a form:

<form name="frm" action="#" autocomplete=off onSubmit="getIt();return false;">
   <fieldset>     
    <label for "id">Enter name:</label>
    <input size="20" type="text" id=’id’ name="name" value='’><BR>   
    <input type="submit" name="doit" value="submit">
    </fieldset>
</form>

The submit even will call a JavaScript function getIt(). We’ll get to it later.

2. Create a div

<div id=result> </div> 

3. Get a reference to XMLHttpRequest object.

    function getHTTPObject() {
        if (typeof XMLHttpRequest != ‘undefined’)
        { return new XMLHttpRequest(); }
        try { return new ActiveXObject("Msxml2.XMLHTTP"); }
        catch (e)
        { try { return new ActiveXObject("Microsoft.XMLHTTP"); }
        catch (e) {} }
    return false; }

    var xmlhttp = getHTTPObject();
        

 4. Create a getIt()  function:

function getIt( ) {              
        if( xmlhttp) {
            var url =’servlet/myClass’;
            var target = document.getElementById("id");            
            url += "?id=" + encodeURIComponent(target.value);
            xmlhttp.open(’GET’, url, true);
            xmlhttp.send(null);
           
            var divResult =document.getElementById(’result’);              
            xmlhttp.onreadystatechange = function (){

                if (xmlhttp.readyState == 4) {
                       if (xmlhttp.status == 200) {                           
                            divResult.innerHTML = xmlhttp.responseText;
                   }   
                } 

           }

        }                
    }    

Code, javascript, ajaxJuly 11, 2007 7:53 pm

Here’s a simple way to generate an hourglass on demand, regardless of what the mouse is over.
Create a document-element class:

html.waitCursor * { cursor: wait; }

When the <html> tag has a class of "waitCursor", the mouse would become an hourglass over the entire page and all elements, including any margin outside the BODY area. Create a pair of simple functions that can be called in global scope:

function beginWait { document.documentElement.className = ‘waitCursor’; }
function endWait { document.documentElement.className = ‘’; }

From John Black on http://swik.net/Ajax/Ajax+Mistakes 

Code, javascriptJune 28, 2007 6:59 pm

Sean McManus wrote a nice routine to implement a delay in JavaScript code:

 

 function pausecomp(millis)
{
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); }
        while(curDate-date < millis);
}

 

Code, javascript, firefox 1:56 pm

"Permission denied to set property XULElement.selectedIndex"

This bug may occur in Firefox when trying to use select() or focus() on an input box in Firefox.

It is fixed by turning autocomplete off:

obj.setAttribute(’autocomplete’,'off’);

 

Code, javascriptJune 20, 2007 3:54 pm

I use this function from http://sedition.com/perl/javascript.html 

function randomColor(){
   var rgbColor = ‘’;
   for ( i = 1; i < 4; i++ ) {
      rgbColor +=  Math.floor(Math.random() * (250+1));
      if ( i != 3 ) rgbColor += ‘,’;
   }
   //window.status = rgbColor;
   return"rgb("+rgbColor+")";
 }

 Usage example:

element.style.backgroundColor = randomColor();