I'm trying to load an image asynchronously using jquery javascript framework. The loaded image should be faded in when it's completely downloaded to local page. By now I'm able to asynchronously load an image and fade it in after a constant time not when its completely downloaded. This produces some graphical errors while fading if image is tall and download takes a moment of time because of image size. Also the memory allocated by the browser is increasing step by step when a image is loaded asynchronously. Even the same images shown before allocates new memory.
How can I load an image asynchronously and do some fading when it's completely downloaded. And how do I have to load the image to get no memory leak in my browser.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<title>jQuery demo</title>
</head>
<body>
<script src="jquery-1.8.0.min.js"></script>
<script src="jquery.timer.js"></script>
//<script src="jquery.center.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<div class="hide">
<img id="bild" height=100% src="logo.jpg" alt="Logo" />
</div>
<script>
var timer = $.timer(function()
{
var img = $('#bild').attr('src','http://localhost/test.php?'+(new Date()).getTime()).load(function()
{
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
$('#bild').attr('src','logo.jpg'); //Show logo in error case
} else {
$("#div.hide").append(img);
}
}).stop(true,true).fadeIn(1000).delay(3000).fadeOut(1000);
});
$("#bild").error(function()
{
$('#bild').attr('src','logo.jpg');
});
timer.set({ time : 5000, autostart : true });
</script>
</body>
</html>
Try this:
if($('#bild').prop('complete')) // if image is already in cache
{
// your code
$(this).fadeIn(1000).delay(3000).fadeOut(1000);
}
else{
$('#bild').load(function(){ // works when image is loaded and not present in cache
// your code
$(this).fadeIn(1000).delay(3000).fadeOut(1000);
});
}
thanks for your code examples. After some tries with it and some further help from a friend we get it working. Here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<title>jQuery demo</title>
</head>
<body>
<script src="jquery-1.8.0.min.js"></script>
<script src="jquery.timer.js"></script>
//<script src="jquery.center.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<div id="imageWrapper" class="hide">
<img id="bild1" style="height: 100%;" src="logo.jpg" alt="Logo" />
<img id="bild2" style="height: 100%; display: none;" src="logo.jpg" alt="Logo" />
</div>
<script>
setImage($('#bild2'));
var timer = $.timer(function()
{
var visible = $('#imageWrapper img:visible');
var hidden = $('#imageWrapper img:hidden');
if (!hidden[0].complete || typeof hidden[0].naturalWidth == "undefined" || hidden[0].naturalWidth == 0)
hidden.attr('src','logo.jpg'); //Show logo in error case
if(hidden.attr('src')!= visible.attr('src'))
{
visible.fadeOut(1000, function() {
setImage(visible);
hidden.fadeIn(1000);
});
}
else
setImage(hidden); //don't fade if current and next picture are the same (e.g. error pic -> error pic), but try to set new image
});
$("#imageWrapper img").error(function()
{
$(this).attr('src','logo.jpg');
});
timer.set({ time : 5000, autostart : true });
function setImage(img)
{
img.attr('src','http://localhost/test.php?'+(new Date()).getTime());
}
</script>
</body>
</html>
www.farinspace.com/jquery-image-preload-plugin/
That jQuery plugin will do what you're looking for. You have callback functions for each image load event, then another callback for when all images are done loading.
$imgs.imgpreload({
each: function() {
// an image loaded, you could fade in each one
},
all: function(){
// all images loaded, you could do something else here
}
});
alternatively you can preload the images so they start downloading before the browser reaches them in the DOM.
Related
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Coupon Page</title>
<script type="text/javascript">
function printCoupon() {
var timeout = 1000;
self.focus();
window.print();
setTimeout("self.close()", timeout);;
self.focus();
}
</script>
</head>
<body onload="printCoupon();">
<p><img src="https://nebula.phx3.secureserver.net/2247f0de910e14f95483f60fdae499a0?
AccessKeyId=8BBF3308EC59517C0B34&disposition=0&alloworigin=1" originalattribute="src" originalpath="coupon.jpg" width="585" height="250">
</p>
</body>
</html>
I've searched for html coding to print webpage image only when image (w585 w250), actual size of image, or a related button is clicked. I found coding that works perfectly yet prints my image really out of focus. The coding you show addresses this by stating focus and such, I've worked on this for near a month without success, Please help
You can try media queries in css to print the image.
Check naturalWidth and naturalHeight and compare with image width and height so if they match then print page.
function printCoupon() {
var timeout = 1000;
var naturalWidth = $('#img')[0].naturalWidth;
var naturalHeight = $('#img')[0].naturalHeight;
var width = $('#img').width()
var height = $('#img').height();
if (naturalWidth == width && naturalHeight == height) {
self.focus();
window.print();
setTimeout("self.close()", timeout);;
self.focus();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<body onload="printCoupon();">
<p><img id="img" src="https://nebula.phx3.secureserver.net/2247f0de910e14f95483f60fdae499a0?
AccessKeyId=8BBF3308EC59517C0B34&disposition=0&alloworigin=1" originalattribute="src" originalpath="coupon.jpg" width="585" height="250">
</p>
the add class is not working even if it is in document ready. I tried both with document ready and without it. it is not working but alert is working.
var $jbanner = jQuery.noConflict(true);
if ($jbanner(window).width() < 1200) {
alert("Less than 1200");
$jbanner("#wad").addClass("hide");
}
other code
var $jbanner = jQuery.noConflict(true);
$jbanner(document).ready(function () {
if ($jbanner(window).width() < 1200) {
alert("Less than 1200");
$jbanner("#wad").addClass("hide");
}
})
With document ready function even the alert box is not working. is it conflicting with other jquerys in the page.
#wad is an image
<img id="wad" src="images/banner.jpg"/>
thanks
ok this should be pretty easy, but not working for me. I just pasted what i am trying to do in a separate html file. but still not working, any help is appreciated.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.js"></script>
<script type="text/javascript">
var $jbanner = jQuery.noConflict(true);
if ($jbanner(window).width() < 1200) {
alert("Less than 1200");
$jbanner("#wad").addClass("hide");
}
else {
alert("greater than 1200");
$jbanner("#wad").addClass("show");
}
</script>
<style type="text/css">
.hide{display:none;}
.show{display:block;}
</style>
</head>
<body><div>
<div id="wallpaperad">
<a href="http://www.yaho.com" target="_blank" rel="nofollow">
<img src="http://www.placehold.it/160x160" alt="banners" id="wad" /> </a>
</div>
</div>
</body>
</html>
I am just trying to create a floating banner ad. that hides for smaller screen sizes.
Try to without jbanner.
$("#wad").addClass("hide");
I want to change an image's src on click of a link. I got a javascript snippet and tried to integrate it but it doesn't work.Im
Here's my HTML:
<html>
<head>
<meta charset="utf-8">
<link href="styles/main.css" rel="stylesheet" type="text/css">
</head>
<body>
<script src="styles/script.js"></script>
<img id="bgimage" src="images/1.jpg"/>
<nav id="nav">A | B |
</nav>
</body>
</html>
Here is my script.js:
var imageId = document.getElementById("bgimage");
function changeImage() {
if (imageId.src == "images/1.jpg")
{
imageId.setAttribute("src","images/2.jpg");
}
else
{
imageId.setAttribute("Src","images/1.jpg");
}
}
This issue is occurring because the script appears in the html before the <img> element. Therefore, the code tries to find the img element, but it can't because the js code executes before the rest of the html is parsed. Correct it by putting the js include tag just before </body>:
<html>
<head>
<meta charset="utf-8">
<link href="styles/main.css" rel="stylesheet" type="text/css">
</head>
<body>
<img id="bgimage" src="images/1.jpg"/>
<nav id="nav">A | B |
</nav>
<script src="styles/script.js"></script>
</body>
</html>
Or, you might want to use DOMContentLoaded to wait until the html has been parsed. Change the js to this, in that case:
var changeImage;
document.addEventListener('DOMContentLoaded',function(){
var imageId = document.getElementById("bgimage");
changeImage=function() {
if (imageId.src == "images/1.jpg")
{
imageId.setAttribute("src","images/2.jpg");
}
else
{
imageId.setAttribute("Src","images/1.jpg");
}
}
},false);
Or you could call document.getElementById() every time changeImage is called
You must place your script just before </body>, or run it at onload.
If not, you run
var imageId = document.getElementById("bgimage");
before loading the image to the DOM, so imageId is null.
Anyway, you could improve your function to
var images = ["images/1.jpg", "images/2.jpg" /*, ... */];
function changeImage() {
imageId.src = images[(images.indexOf(imageId.src)+1) % images.length];
}
So I am doing something very basic that can be done with CSS but I want to do it with jQuery to get familiar with the library.
I am trying to create a rollover image gallery. Where when you put the mouse over the image it will be swapped with a slightly edited version of it.
Here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery</title>
<script src="jquery-1.9.1.js"></script>
<style>
</style>
</head>
<body>
<div id="gallery">
<img src="images/one_s.jpg" />
<img src="images/two_s.jpg" />
<img src="images/three_s.jpg" />
<img src="images/four_s.jpg" />
<img src="images/five_s.jpg" />
<img src="images/six_s.jpg" />
</div>
<script>
$(document).ready(function(){
var alternate = ['images/one_s_edited.jpg',
'images/two_s_edited.jpg',
'images/three_s_edited.jpg',
'images/four_s_edited.jpg',
'images/five_s_edited.jpg',
'images/six_s_edited.jpg'];
var $selection = $("#gallery img");
for(var i = 0; i < alternate.length; i++)
{
var imgObject = new Image();
var downloadedImg = imgObject.src = alternate[i];
console.log(downloadedImg);
var originalSrc = $selection.eq(i).attr("src");
console.log(originalSrc + "\n");
$selection.eq(i).hover(
function(){
$(this).attr("src", downloadedImg);
},
function(){
$(this).attr("src", originalSrc);
}
);//End hover
}//End loop
});//End ready
</script>
</body>
</html>
Here is a link to the final result: link
As you can see it rolls over but not as planned. It ends up with the last rollover-image and doesn't change back to the original nor does it show the appropriate rollover image that corresponds with it.
Any simple suggestions without using regular expressions?
The problem is the wrong usage of a closure variable in a loop.
But the solution can be simplified to
$(document).ready(function () {
var $selection = $("#gallery img");
$selection.hover(function () {
this.src = this.src.replace('.jpg', '_edited.jpg')
}, function () {
this.src = this.src.replace('_edited.jpg', '.jpg')
})
}); //End ready
I am building a phonegap app using javacsript and jquery.I wrote this piece of code to swipe images.
$('#fullscreen').swipeleft(function () {
//Show next image
showNext();
alert('Left');
});
function showNext() {
$("#fullscreen").attr('src', "images/next.png");
}
But when I swipe, the image doesn't change and I get the error "09-13 14:49:21.188: W/webview(20238): Miss a drag as we are waiting for WebCore's response for touch down."
After browsing through some forums I added the following code.
var fullScr = document.getElementById("fullscreen");
fullScr.addEventListener( "touchstart", function(e){ onStart(e); }, false );
function onStart ( touchEvent ) {
if( navigator.userAgent.match(/Android/i) ) {
touchEvent.preventDefault();
}
}
But it still doesn't work.Although when I change my screen orientation from portrait to landscape, the image changes.
What is it that happens when I change the orientation and how could I get it working in the same orientation (portrait/landscape) please?
Thanks in advance.
Well it worked for me :S... I used version 1.5.0 of Cordova and run the app on Android simulator 4.0.3. Could you try the following example?
HTML content:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<!-- BASIC INCLUDES - TO BE MODIFIED ACCORDING TO YOUR CONVENIENCE -->
<link rel="stylesheet" href="./css/jquery.structure-1.1.0.min.css" />
<link rel="stylesheet" href="./css/jquery.mobile-1.1.0.min.css" />
<script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js"></script>
<script type="text/javascript" src="./js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="./js/jquery.mobile-1.1.0.min.js"></script>
<!-- END - BASIC INCLUDES -->
<script type="text/javascript" charset="utf-8">
$(function() {
$('#fullscreen').swipeleft(function () {
//Show next image
showNext();
});
function showNext() {
$("#fullscreen").attr('src', "./images/next.png");
}
});
</script>
</head>
<body>
<div data-role="page">
<div data-role="content">
<img id="fullscreen" src="./images/previous.png"></img>
</div>
</div>
</body>
</html>
NB: Make sure of the following things:
Modify the source of the "basic includes" of the code to your convenience (source of the CSS / JS files of jQuery / jQuery Mobile)
Change the source of the version of cordova if yours is not 1.5.0
Hope this will work for you too. Anyway, let me know about your result.