Wednesday, October 13, 2010

[Javascript][Html] Attach a Loading Image

In Javascript, create a function to show the division and attach the loading image to it:

function attachLoadImgText(txt) {
var text = document.createTextNode(txt);

// NOTE: to make the loading gif working for IE, we MUST use the innerHTML trick...
$('loading').innerHTML = ''<img id="loadingImg" src="/images/loadinfo.gif"/>';
$('loading').appendChild(text);
$('loading').style.display = 'block';
}

In Html, create a division that will hold the image later, with display:none

<div id="loading" style="display: none; font-size: 14px"><img id="loadingImg" src="/images/loadinfo.gif" ></div>


NOTE:

In my example I used the Javascript Prototype, to do it in an old-fashioned Javascript style, use var load = document.getElementById('loading'); load.innerHTML = ...


Here is a very cool Loader Generator I found on the web, hope you find it useful as well :)

3 comments:

Hibino said...

既然已经要放一段html进去页面了,那就直接把要放文字的地方也塞进去,就不需要用js建立文字了。
[div id="loading" style="display: none; font-size: 14px"][img id="loadingImg" src="/images/loadinfo.gif" /][span id="loading_txt"][/span][/div]


然后你的function可以是
var loading = {
show: function( txt ){
$( 'loading_txt' ).innerHTML = txt;
$( 'loading' ).show();
},
hide: function(){
$( 'loading' ).hide();
}
}

就能用loading.show( 'abcd' )和loading.hide()来控制你的loading了

nana said...

那样对IE不管用,如果只是支持firefox之类的就很完美。

Anonymous said...

对IE当然管用呀。。。。。。。ie在这些方面还是没有bug的