Tuesday, May 5, 2009

JQuery - Part 3 Dynamic object loading

This post is about loading a control dynamically through Jquery scripts.

The powerful feature of Jquery selectors combined with CSS scripts enables the client side loading of controls with less coding/effort.

I recently incorporated this featur in one of the projects where we had a requirement to dynamically change the image at run time based on the result set from the database query. I would not want to write server side code to determine the image, Instead i started to research about loading the image through Jquery selectors.

The project required to load the image at one of the table column < td >.

I declared a placeholder client side div with a id "loadImage".
"< td >
< div id="loadImage" >
< %# DataBinder.Eval(Container.DataItem, "Flag").ToString().Trim()% >
< /div >
< /td >"

On the document ready event i wrote the Jquery funtion which will locate the position of the DIV and load the image on the particular DIV as below.

$(document).ready(function() {

$('#tbl_temp tr').each(function() {

var valueee = $(this).find('div');
var txt = jQuery.trim(valueee.text());

var imgSrc = "";
if (txt == 'G') {
imgSrc = 'images/green_icon.gif'

else if (txt == 'O') {
imgSrc = 'images/gray_icon.gif'
else {

if (imgSrc.length > 0) {
var img = new Image()
$(img) // once the image has loaded, execute this code

.load(function() {

//.text = '';
// remove the loading class (so no background spinner),
// then insert our image
// fade our image in to create a nice effect
}) // if there was an error loading the image, react accordingly
.error(function() {
// notify the user that the image could not be loaded
// set the src attribute of the new image to our image
.attr('src', imgSrc)
.css({ 'border': 'none' });

No comments: