开发者

How to make Alert to run after the image is loaded?

I have this code and I want that the alert will pop up only after the backgroundImage is loaded.

$('#element').click(function(){
    $('#element').css开发者_运维问答({
        backgroundImage: "url('http://www.button.jpg')",
        backgroundRepeat: 'no-repeat',
        backgroundPosition: '7px 5px'});;

alert ("button is loaded");

The button.jpg is a small size: 3 KB.

But when I click on the button element, first the ALERT pop up, and 2 seconds after the image is complete loding.

I read about callBack

Also about Delay()

Also about timeout

But I am new in coding, and didn't understand what and how should I do here.


You would set up a load event on the image first.

var imgSrc = 'http://www.button.jpg';

$('#element').click(function() {

    var img = new Image,
        element = $(this);

    img.onload = function() {

        element.css({
            backgroundImage: "url('" + imgSrc + "')",
            backgroundRepeat: 'no-repeat',
            backgroundPosition: '7px 5px'
        });

        alert("button is loaded");

    }

    img.src = imgSrc;

});

jsFiddle.

Then, when the image has been loaded, the load callback will be called and the background will be updated.

If you need to support IE6 and are finding it won't cooperate by downloading the image again you may need to look into a workaround.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜