A good explanation of the JavaScript event delegation can found in this SitePoint article.
A good explanation of the JavaScript event delegation can found in this SitePoint article.
Adjusting the left property will have no effect on the matching elements unless those elements have their CSS position set to relative or absolute. The default CSS position for all block‑level elements is static.
If you put an absolutely positioned box inside a relatively positioned box, it moves with that box. It is absolutely relative!
Prevent browser from jumping to top of the page
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.
Rounded Corners In Forms With CSS and JavaScript
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;
$(’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.
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.
How to use default options in Prototype
An excellent explanation can be found here.
An interesting note on a problem with opening chm files and a simple solution:
http://www.nik.com.au/archives/2005/04/06/chm-help-files-error-the-page-cannot-be-displayed/
Create Striped Lists in Prototype and Jquery
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");
});
Creating striped lists/tables in JSTL
The JSTL iterator exposes a varStatus variable that holds the loop status. With this information at hand, we can constuct the following JSTL loop to create a list with alternate colors.
<ul>
<c:forEach var="row" items="${queryResults.rowsByIndex}" varStatus=’vs’>
<c:choose>
<c:when test= "${vs.index % 2 == 0}">
<li class=’even’>
</c:when>
<c:otherwise>
<li>
</c:otherwise>
</c:choose>
<c:out value="${row[0]}"/>
</li>
</c:forEach>
</ul>
The test condition checks whether the index property of varStatus variable is even or odd, and assigns a css class named ‘even’ to each even item.
You can easily substitute table rows for li elements in this example.
Difference Between 2 Dates in JavaScript
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);
Here is a compact generic function by john.ellingsworth that generates a table from a PEAR DB result set. It even uses column names as HTML table column headings.
A hint: to better format a table when there is a null value in the resultset, add a ‘nbsp;’ character to a table cell before a field value.
JSTL has a set of pre-defined objects such as pageScope, requestScope, param, paramValues and cookie.
If you have a cookie named ‘myCookie’, you can obtain its value as follows:
<c:out value="${cookie.myCookie.value}"/>
Custom Attributes for HTML Tags
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.
Get a reference to all text fields in JavaScript
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;
}