I want to display two images that I have no idea when they will be generated. So I want to use the jquery error function to keep checking if the images exist, and display each. Following code works on every browser except IE. Why does it not work on IE, really appreciate your help.
<style type="text/css">
DIV#loader {
width: 500px;
height: 500px;
overflow: hidden;
}
DIV#loader.loading {
background: url(spinner.gif) no-repeat center center;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
var image_names = new Array(2);
image_names[0] = 'a.jpg';
image_names[1] = 'b.jpg';
var divs = document.getElementsByTagName("div");
for ( var i = 0; i < divs.length; i++) {
showImage(image_names[i], divs[i]);
}
});
function showImage(src, div) {
var img = new Image();
$(img).load(function() {
$(this).hide();
$(div).removeClass('loading').append(this);
$(this).fadeIn();
}).error(function() {
setTimeout(function() {
$(img).attr('src', src);
}, 2000);
}).attr('src', src);
}
</script>
This is the HTML body
<body>
<h1>Image Loading</h1>
<div id="loader" class="loading"></div>
<div id="loader" class="loading"></div>
</body>
It seems like IE does not know the image is generated if it does not exist when the page first loads
It's the $(document).ready({}) part; throws an error in ie for me. Changing it to $(function(){}); seems to work for me at least in IE.
Caching caused the problem. Changed the src to:
$(img).attr('src', src + "?" + (new Date().getTime()));
Related
was trying to follow a guide that seemed to me very straightforward and simple that i found here:
Change css background-Image using javascript
however in my implementation it doesn't work. the image does not get displayed or changed. any hints?
EDIT: not the same as suggested duplicate. now that parenthesis after changeImage has been removed, the function gets repeated but the problem of not displaying any of the background images persists.
2ND EDIT: i also tried removing the parenthesis after buildImage, with the same result (no background images displayed)
<div id="pupa">
</div>
<script>
var images = ['file:///Users/karin/PROJECTS/PORTFOLIO/pupal%20stage/img/stage12.jpg',
'file:///Users/karin/PROJECTS/PORTFOLIO/pupal%20stage/img/stage34.jpg',
'file:///Users/karin/PROJECTS/PORTFOLIO/pupal%20stage/img/stage56.jpg'];
var index = 0;
function buildImage() {
console.log("setting image");
document.getElementById('pupa').style.backgroundImage = 'url(' + images[index] + ')';
}
function changeImage() {
index++;
if (index >= images.length) index = 0;
console.log("changing image");
document.getElementById('pupa').style.backgroundImage = 'url(' + images[index] + ')';
}
buildImage();
setInterval(changeImage, 3000);
</script>
This code will work if you add your images in a folder called img in the same folder where the html page is.
<html>
<head>
<style>
#pupa
{
width:300px;
height:300px;
background-position:center;
background-repeat:no-repeat;
background-size:cover;
}
</style>
</head>
<body>
<div id="pupa"></div>
<script>
var images = ['img/stage12.jpg',
'img/stage34.jpg',
'img/stage56.jpg'];
var index = 0;
document.getElementById('pupa').style.backgroundImage = `url(${images[index]})`;
setInterval(function(){
index=(++index >= images.length)?0:index;
console.log(`changing image of index : ${index}`);
document.getElementById('pupa').style.backgroundImage = `url(${images[index]})`;
},3000);
</script>
</body>
</html>
This is the same code tweaked a bit, and you don't need another function buildImage() to set image first, it works (make sure to check path of images)
Make sure to change width, height, background-size, image name, path etc according to your need.
I am using Jimdo and have a given div (containing 3 sub-divs, I think this is my general problem, but I am not sure) I found with the browser:
<div class="jtpl-background-area jqbga-container jqbga-web--image" background-area="" style="background-image: url('https://image.jimcdn.com/app/cms/image/transf/dimension=767x/path/s4354a59fbfee63e4/backgroundarea/ibb91266a7f033fa3/version/1529172695/image.jpg');background-position: 54.0833% 41.0025%;"></div>
How do I get a function triggered after the background-image of this is loaded?
I've already spent hours into this, tried tons of ways I found here or tools like waitforimages - still without success. What is going on with Jimdo / this div?
How do I get something triggered after the background-image is loaded?
var src = $('.jtpl-background-area').css('background-image');
var url = src.match(/\((.*?)\)/)[1].replace(/('|")/g,'');
var img = new Image();
img.onload = function() {
$('.jtpl-background-area').css('-webkit-animation', 'fadein 4s');
}
img.src = url;
if (img.complete) img.onload();
does not work.
$('.jtpl-background-area').waitForImages(true).done(function() {
$('.jtpl-background-area').css('-webkit-animation', 'fadein 4s');
});
does not work (waitforimages-script is included correct and opacity of .jtpl-background-area is set to 0 in css).
Any ideas?
$(window).on('load', function() {
$(".jtpl-background-area").css('-webkit-animation', 'fadein 4s');
});
causes backgrounds often popping up too late. Page is displayed while pictures are still not ready/fully loaded.
-
Edit:
Regarding Scott Marcus and the answer here by 'adeneo' (Wait for background images in CSS to be fully loaded):
$(window).on('load', function() {
$(".jtpl-background-area jqbga-container jqbga-web-
image").ready(function() {
$(".jtpl-background-area").velocity({ opacity: 1 },{ duration: 3000});
})
});
This here "works" - but my bg-images popping up too late.
But why does nothing happen if I exchange this with
var src = $(".jtpl-background-area jqbga-container jqbga-web-image");
var url = src.match(/\((.*?)\)/)[1].replace(/('|")/g,'');
var img = new Image();
img.onload = function() {
$('.jtpl-background-area').velocity({ opacity: 1 },{ duration: 3000});
}
img.src = url;
if (img.complete) img.onload();
?
Where is my mistake? Why doesnt this work and make my page stuck? It stays white and fails to load at all with this code.
Or in other words - how do I get
var src = $('#test').css('background-image');
var url = src.match(/\((.*?)\)/)[1].replace(/('|")/g,'');
var img = new Image();
img.onload = function() {
alert('image loaded');
}
img.src = url;
if (img.complete) img.onload();
to work with my (given and unchangeable)
<div class="jtpl-background-area jqbga-container jqbga-web--image" background-area="" style="background-image: url('https://image.jimcdn.com/app/cms/image/transf/dimension=767x/path/s4354a59fbfee63e4/backgroundarea/ibb91266a7f033fa3/version/1529172695/image.jpg');background-position: 54.0833% 41.0025%;"></div>
exactly?
Instead of using a background image, you can use an img element and CSS positioning to layer it behind the content of its parent div. Then, you can use the load event of the img element.
document.querySelector(".jtpl-background-area").addEventListener("load", function(){
console.log("Background loaded!");
$(".hidden").fadeIn(4000); // Fade the image in
});
/* by positioning the element absolutely and giving it a negative
z-index, we put it behind any other items in the same space. */
.jtpl-background-area { position:absolute; z-index:-1; top:0; left:0; }
div div { background-color:rgba(255,255,255, .5); }
.hidden { display:none; } /* Image will start off hidden */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>Some other div content</div>
<!-- The image will be hidden at first -->
<img class="hidden jtpl-background-area jqbga-container jqbga-web--image" background-area="" src="http://imgsrc.hubblesite.org/hvi/uploads/image_file/image_attachment/30741/STSCI-H-p1821a-m-1699x2000.png">
</div>
So here is what I came up with. We are basically creating an image, waiting for the file to load, then applying a style to the container.
Basically, we are making sure that no background-image is shown when the page loads by setting background:none !important; to the container.
We then create a new Image with JS, once that image's source is loaded, we apply a new class to the container, which sets the background image. You can add the animation and/or the opacity at your own discretion.
You may or may not have to fiddle around with the !important flag for your use case.
Is this what you had in mind?
$(document).ready(function() {
var img = new Image();
var container = $('.container');
img.src = "https://placeimg.com/640/480/any";
img.addEventListener('load', function() {
container.addClass('hasBackgroundImage')
});
});
.container {
opacity: 0;
background: none !important;
}
.hasBackgroundImage {
opacity: 1;
background-image: url('https://placeimg.com/640/480/any') !important;
background-size: cover;
height: 500px;
width: 500px;
transition: all ease-in-out 4s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
You might do it like this:
Script starts working before the document has been loaded.
It intercepts the inline style of your div before it's been applied.
Then uses Image object to load the image and sets the background-image onload.
var i = setInterval(function() {
var div = document.querySelector('.jtpl-background-area');
if (div) {
clearInterval(i);
var src = div.style.backgroundImage.replace(/^url\(['"]?|['"]?\)/ig, '');
div.style.backgroundImage = 'none';
var img = new Image();
img.onload = function() {
div.style.backgroundImage = 'url(' + src + ')';
div.classList.add('loaded')
img = null;
}
img.src = src;
}
}, 10);
.jtpl-background-area {
width: 330px;
height: 200px;
opacity: 0;
}
.loaded {
transition: opacity 2s linear;
opacity: 1;
}
<div class="jtpl-background-area jqbga-container jqbga-web--image" background-area="" style="background-image: url('https://image.jimcdn.com/app/cms/image/transf/dimension=767x/path/s4354a59fbfee63e4/backgroundarea/ibb91266a7f033fa3/version/1529172695/image.jpg');background-position: 54.0833% 41.0025%;"></div>
Hope this helps.
I have set up a piece of javascript that is meant to operate as a slideshow where you have to click right or left to go each way through an array of images. As it is, it only has 3 images and one button (the blue div) for going one way through the array.
I have scoured this code over and over and tried to separate the pieces of it but I could discern no pattern over what works. I have been stuck at this stage for months, and would therefore really appreciate some help.
<!DOCTYPE HTML>
<html>
<head>
<style>
#clicker { width: 200px; height:200px; background: blue; }
#pic { width: 300px; height: 150px; }
</style>
</head>
<body>
<div id="clicker"></div>
<img id="pic" src="models_web.jpg" alt="Icon" />
<script type="text/javascript">
var imgs = ["models_web.jpg","reflex_2.jpg","blue_web.jpg"];
var i = 0;
var addl = document.getELementById("clicker");
function clickrotate() {
document.getElementById("pic").src = imgs[i];
i++
if (i === 2) {i = 0};
}
addl.addEventListener( "click", clickrotate, false ) ;
</script>
</body>
</html>
You have a typo in your script.
var addl = document.getELementById("clicker");
change to var addl = document.getElementById("clicker");
Another thing, your counter increment is wrong. It will reset after viewing the second image, because you check i === 2 after incrementing it.
If you check the console in the developer tools in any modern browser, you will see what's wrong. It will save you the headaches next time.
I cannot find the correct solution for me, none of what I tried is working :(
I need:
before showing page content get screen resolution and then, according to it, resize all img-s on a page.
Ok, what I've tried:
<script type="text/javascript">
$(window).load(function() {
var img = document.images;
if (screen.width <= 699) {
for (var i = 0; i < img.length; i++) {
img[i].height = 200px;
img[i].width = 200px;
}
}
})
</script>
Some very old fashioned JavaScript should do the trick.
<script>
if(screen.width > 699) {
document.write('<style>img { width: 200px; height: 200px; }</style>');
}
</script>
Although rethinking your design philosophy would be better! Remember that some people might not have their browser maximised, or might want to set their own zoom settings.
My code has an animated GIF (loading image)
I get the html page in a variable "data" from Ajax call.
$("#content").html(data); // takes about 5 seconds and the GIF animation freezes since IE is single threaded.
Is there a way to write the data line by line with a setTimeout / setInterval function so that the thread is released for a brief moment so that the animation continues?
Fiddle URL:
http://jsfiddle.net/deepakssn/Kp2bM/
Alternate solution I tried:
<style>
#loading {
background: url(loading.gif) no-repeat center center #fff;
display: block;
position: fixed;
height: 500px;
width: 500px;
}
</style>
<script src="../scripts/jquery.js"></script>
<script>
$(window).load(function () {
function writeData(data) {
var yourLines = data.split("\n");
for (var i = 0, j = yourLines.length; i < j; i++) {
var x = setTimeout(function() {
$("#content").append(yourLines[i]);
console.log("Line No :"+[i]+" "+Date.now());
}, 5000);
}
}
function ajaxLoad() {
$.ajax({
url: "test.txt"
}).done(function (data) {
console.log("success"+Date.now());
writeData(data);
//$("#content").html(data);
console.log("loaded data"+Date.now());
});
}
ajaxLoad();
});
</script>
<div id="loading"></div>
<div id="content"></div>
I ran into this problem while adding a 'loading' indicator for one of my projects. I used this which solved the problem for me. Since it's not an image, it doesn't freeze.