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.
I read about callBack
Also about Delay() Also about timeoutBut 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.
精彩评论