I'am using the following javascript code to implement image-loaded-show function in mobile web browser (supporting HTML5). Image-loaded-show means that before the image is completely loaded, the width and height is 0, namely it willn't show and occupy any space.
Now the problem is that the images will not show until all the images are loaded.
What I need is that the iamge in the page is seperate, once loaded, the image show up.
Any tips on how to modify this javascript code? thanks.
<script type='text/javascript'>
var srcs = [];
window.doBindLinks = function() {
var elems = document.getElementsByTagName('img');
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
var link = elem.getAttribute('src');
elem.setAttribute('link', link);
elem.removeAttribute('width');
elem.removeAttribute('height');
elem.removeAttribute('class');
elem.removeAttribute('style');
if(link.indexOf('.gif')>0)
{
elem.parentNode.removeChild(elem);
}else{
}
}
var content = document.getElementById('content');
var images = content.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
srcs[i] = images[i].src;
loadImage(images[i], srcs[i],
function (cur, img, cached) {
cur.src = img.src;},
function (cur, img) {
cur.style.display = 'none';});
}
};
var loadImage = function (cur, url, callback, onerror) {
var img = new Image();
img.src = url;
img.width = '100%';
if (img.complete) {
callback && callback(cur, img, true);
return;
}
img.onload = function () {
callback && callback(cur, img, true);
return;
};
if (typeof onerror == 'function') {
img.onerror = function () {
onerror && onerror(cur, img);
}
}
};
</script>
The source code of the page is :
<body onload="doBindLinks();"><div id="content"> images and text </div></body>
P.S: Because I need to write this javascript string in C#, I replace the (") into (').
Edited:
Is the following right:
window.doBindLinks = function() {
var elems = document.getElementsByTagName('img');
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
var link = elem.getAttribute('src');
elem.setAttribute('link', link);
elem.removeAttribute('width');
elem.removeAttribute('height');
elem.removeAttribute('class');
elem.removeAttribute('style');
elem.setAttribute('display','none');
if(link.indexOf('.gif')>0)
{
elem.parentNode.removeChild(elem);
}else{
}
elem.attachEvent('onload',onImageLoaded);
}
};
window.onImageLoaded = function() {
var elem = event.srcElement;
if ( elem != null ) {
elem.setAttribute('display','block');
}
return false;
};
Besides, the css code is:
img {width: 100%; border-style:none;text-align:center;}
But the images still wouldn't show until all are loaded.
I'm not 100% sure I understand your question. Are you trying to hide the image until it is fully loaded? Are you writing the images out to the page, or are they already in the page? Here are a couple of options:
set style="display:none". Then add onload="this.style.display='';" event listener to image.
images will each show as they are loaded.
if you are able to change the c# code, then simply write all the image urls out as a list of strings into an imageload function. Then use this function to create the images and add them to the content div.
I hope this helps you. If not, please provide more context, and I will try to help farther.
Ok, I see where you are going now. You can take out all that javascript that you have written. Maybe print it out so that you can throw it in the trash. Then take my example here... and it will do the trick for you. each image shown only as it is loaded. Obviously if you want to change any other properties you can do it in the showImage function. hope this helps.
<html>
<head>
<style>
img{display:none;}
</style>
<script type="text/javascript">
function showImage(elem) {
elem.style.display = 'block';
}
</script>
</head>
<body><div id="content">
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
</dvi>
</body>
</html>
Related
I'm a noob working my way to learn JavaScript on my own and using some resources but want to probe things on my own hence trying this thing but it's not working for some reason. Help is appreciated.
The object is to clarify some blurred images by swapping the source. The images are called zero.jpg/zeroblur.jpg, one.jpg/oneblur.jpg and so on... The page loads with blurred image sources until clicked on. I want to write code so that it goes back to original blurred source image after 5 secs.
P.S.: The code in comments is what I've tried to write on my own.
window.onload = init;
function init() {
var blurryPic = document.getElementsByTagName("img");
for (var i = 0; i < blurryPic.length; i++) {
blurryPic[i].onclick = clarify;
// setTimeout(resetPic, 5000);
}
}
function clarify(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + ".jpg";
pic.src = id;
}
// function resetPic(eventObj) {
// var pic = eventObj.target;
// var id = pic.id;
// id = "images/" + id + "blur.jpg";
// pic.src = id;
// }
It's better with CSS: your image stays the same and you only toggle a class, the class making your image blur.
document.getElementById("clickImg").addEventListener("click", function() {
this.classList.toggle("blurImg")
})
.blurImg {
-webkit-filter: blur(5px); /* Safari 6.0 - 9.0 */
filter: blur(5px);
}
<img src="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" id="clickImg">
If what you want is really to be able to reset the original image, I think it's better to stock it in a specific attribute, like this:
document.getElementById("reset").addEventListener("click", function() {
document.getElementById("clickImg").src = document.getElementById("clickImg").getAttribute('origSrc')
})
var imgs = [
'https://vignette.wikia.nocookie.net/spongebob/images/d/d7/SpongeBob_stock_art.png/revision/latest?cb=20190921125147',
'https://static.vecteezy.com/system/resources/previews/000/072/351/non_2x/spongebob-squarepants-vector.jpg',
'https://upload.wikimedia.org/wikipedia/en/c/c7/BattleForBikiniBottom.jpg'
]
document.getElementById("random").addEventListener("click", function() {
document.getElementById("clickImg").src = imgs[Math.floor(Math.random() * 3)]
})
<input type="button" value="RESET" id="reset" />
<input type="button" value="RANDOM" id="random" /><br/>
<img src="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" origSrc="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" id="clickImg">
I used an if statement for this to check if the first loaded image file was present or not. Then use the attribute src for the file. Here's an example.
#javascript
function magicChanger(){
var myImage = document.getElementById("emailImage")
if (myImage.getAttribute("src") == "first loaded image"){
myImage.setAttribute("src", "second image")
}
else{
myImage.setAttribute("src", "first loaded image")
}
}
#html element
<button id = "emailButton" onclick="magicChanger()">
<img id="emailImage" src="{% static 'GoEnigmaPics/emailIcon.png' %}" alt="email">
</button>
Thanks for all the answers! I wanted to get it done in JS only so CSS wouldn't work. Appreciate the answers and will definitely incorporate in future projects!
P. S. This is what got it done in the end.
window.onload = init;
function init() {
var blurryPics = document.getElementsByTagName("img");
for (var i = 0; i < blurryPics.length; i++) {
blurryPics[i].onclick = clarify;
}
function clarify(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + ".jpg";
pic.src = id;
setTimeout(reBlur, 3000, pic);
}
function reBlur(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + "blur.jpg";
pic.src = id;
}
Please try this code,To Is there a way to switch images src back to original after on.click src change event?
It switches back because by default, when you click a link, it follows the link and loads the page. In your case, you don't want that. You can prevent it either by doing e.preventDefault();
$(function() {
$('.menulink').click(function(){
$("#bg").attr('src',"img/picture1.jpg");
return false;
});
});
I hope this code will be useful.
Thank You.
<!DOCTYPE html>
<html>
<head>
<meta charset="{CHARSET}">
<title>imagegame</title>
<style>
body { margin: 20px; }
img { margin: 20px; }
</style>
</head>
<body>
<img id="pic1" src="img/charpter9/zeroblur.jpg">
<img id="pic2" src="img/charpter9/oneblur.jpg">
<img id="pic3" src="img/charpter9/twoblur.jpg">
<img id="pic4" src="img/charpter9/threeblur.jpg">
<img id="pic5" src="img/charpter9/fourblur.jpg">
<img id="pic6" src="img/charpter9/fiveblur.jpg">
<script>
function init() {
var imgs = document.getElementsByTagName("img");
for(var i = 0; i < imgs.length; i++){
imgs[i].onclick = onClick;
}
}
function onClick(e){
var img = e.target;
var imgsrc = img.src;
var imgid = img.id;
var imgsrc0 = imgsrc;
imgsrc = imgsrc.replace("blur","");
img.src = imgsrc;
setTimeout(refresh, 5000, imgsrc0, imgid);
}
function refresh(imgsrc,id){
var img = document.getElementById(id);
img.setAttribute("src",imgsrc);
}
window.onload = init;
</script>
</body>
</html>
above is the code, my main consideration is whether there is a plan to solve mouse double-click when clicking on one element whose trigger is onclick.
the error I found is when I double-click the image showed on the page, the pic can't be reblurrd automatically. the case is head-first javascript book chapter 9 on about page 142.
thank for your time.
enter image description here
The main issue is, that the second time the src has no blur anymore already and the time the second timeout is finished it gets set to that src instead of the one with the blur.
You could keep the original source in a data-attribute and set the src back on that attribute. Furthermore you can cancel the setTimeout() on doubleclicks.
function onClick(e){
var img = e.target;
var imgsrc = img.src;
var imgid = img.id;
var imgsrc0 = imgsrc;
//REM: Keep the original src
if(!img.getAttribute('data-img-src')){
img.setAttribute('data-img-src', imgsrc)
};
imgsrc = imgsrc.replace("blur","");
img.src = imgsrc;
//REM: Clear and reassign the timeout
clearTimeout(img.timeout); //REM: Dirty way, but fast to show
img.timeout = setTimeout(refresh, 5000, imgsrc0, imgid)
}
function refresh(imgsrc,id){
var img = document.getElementById(id);
//REM: Set the original src
img.setAttribute("src",img.getAttribute('data-img-src'));
img.removeAttribute('data-img-src')
}
Yet I think it would be much easier to keep all the images in an object and create the img on the fly. Also it makes your code unbound from a fixed naming scheme in your image sources. Like this for example:
var _Images = [
{Blurred: 'https://image.flaticon.com/icons/svg/172/172838.svg', Active: 'https://image.flaticon.com/icons/svg/196/196138.svg'},
{Blurred: 'https://image.flaticon.com/icons/svg/196/196138.svg', Active: 'https://image.flaticon.com/icons/svg/172/172838.svg'},
{Blurred: 'https://image.flaticon.com/icons/svg/172/172838.svg', Active: 'https://image.flaticon.com/icons/svg/196/196138.svg'}
];
window.onload = function(){
for(var i=0, j=_Images.length; i<j; i++){
var tImage = document.body.appendChild(document.createElement('img'));
tImage.src = _Images[i].Blurred;
tImage.setAttribute('width', '20px');
tImage.onclick = function(image){
this.src = image.Active;
window.clearTimeout(image.Timeout);
image.Timeout = window.setTimeout(function(){
this.src = image.Blurred
}.bind(this, image), 5000)
}.bind(tImage, _Images[i])
}
};
I am loading image on button click next and previous
here i have only 2 div which are animating on click of next and previous button with different images coming from database through json.
I am getting my functionality done but it looking fine only on localhost when I am uploading this on server it gets a blank screen between the animation due to image loading actually what happens my div has completed animation and showing next div but image are loaded properly so a blank div is shown
I want to reduce this load time or my screen will show when the image has been loaded completely how can I fix it ?
basically i want a ajax loader which will automatically get remove after loading
Here is my code
<table cellpadding="0" cellspacing="0" border="0" width="815" align="center">
<tr>
<td><div class="btnPrv2" id="btnPrv2"><</div></td>
<td>
<div class="slider">
<div class="mc3" id="mc3" ><img src="" class="ff3" /></div>
<div class="mc4" id="mc4" ><img src="" class="ff4" /></div>
</div>
</td>
<td><div class="btnNxt2" id="btnNxt2">></div></td>
</tr>
</table>
<script>
$(function(){
$(".mc3").animate({left:"-=782px" },350);
$(".mc4").animate({left:"-=782px" },350, function(){ curwdiv = hdiv; canAnim = true});
});
</script>
One way to do it could be load the images when loading the page but keep it hide it using zindex or something like that, then you just need to put it on front and the load time should be longer for loading the page but lesser on the button action.
Could be something like this in your html:
<div class="mc3" id="mc3" style="zindex:-1;" ><img src="" class="ff3" /></div>
And then something like this in your js to show the image (maybe in your function):
$(".mc3").zIndex(inherit);
PD: I think you should look into your ortography and sintax, it is nearly impossible to understand you question.
I've got this plug somewhere,
For example you have
<img class="preload_image" src="#">
<img class="preload_image" src="#">
<img class="preload_image" src="#">
It will count the images, and will check if all of them are already loaded, check the code below.
// .preload_image is the image class that needed to be loaded
$('.preload_image').imagemonitor({
'onLoad': function (loadedImage, totalImage) {
// While loading, progress bar will be shown
$('#load-progressbar img').css('width', Math.floor((loadedImage / totalImage) * 100) + '%');
},
'onComplete': function (loadedImage) {
// After loading, show image
$('#load-display').fadeOut(2000).queue(function () {
$('#content-display').fadeIn(2000);
$(this).dequeue();
});
}
});
Then here's the source code for that.
(function( $ ){
$.fn.imagemonitor = function(imageEvent)
{
var totalImage = 0;
var loadedImage = 0;
var loadedImageSrc = Array();
var imageObject = Array();
var isComplete = false;
var loop_delay = 200; // in miliseconds
var imgElement = this;
if(imageEvent.init == null) imageEvent.init = function(){};
if(imageEvent.onLoad == null) imageEvent.onLoad = function(){};
if(imageEvent.onComplete == null) imageEvent.onComplete = function(){};
function createImageObject()
{
imgElement.each(function(index)
{
imageObject[index] = new Image();
$(imageObject[index]).attr('src', $(this).attr('src'));
});
}
function count_loaded_image()
{
for(var i=0; imageObject[i]; i++)
{
if(!checkIfLoaded($(imageObject[i]).attr('src')))
{
if(imageObject[i].complete || imageObject[i].readyState === 4)
{
loadedImageSrc.push($(imageObject[i]).attr('src'));
loadedImage++;
imageEvent.onLoad(loadedImage, totalImage);
}
}
}
if((loadedImage == totalImage) && !isComplete)
{
isComplete = true;
imageEvent.onComplete(loadedImage);
}
else setTimeout(count_loaded_image, loop_delay);
}
function getTotalImage()
{
var tempImageSrc = Array();
imgElement.each(function(index)
{
var counted = false;
for(i=0; tempImageSrc[i]; i++)
{
if(tempImageSrc[i] == $(this).attr('src')) counted = true;
}
if(!counted) tempImageSrc.push($(this).attr('src'))
});
return tempImageSrc.length;
}
function checkIfLoaded(src)
{
var loaded = false;
for(var i=0; loadedImageSrc[i]; i++)
{
if(loadedImageSrc[i] == src) loaded = true;
}
return loaded;
}
function setOnloadEvent()
{
imgElement.each(function(index)
{
$(this).load(function()
{
if(!checkIfLoaded($(this).attr('src')))
{
loadedImage++;
loadedImageSrc.push($(this).attr('src'));
imageEvent.onLoad(loadedImage, totalImage);
if((loadedImage == totalImage) && !isComplete)
{
isComplete = true;
imageEvent.onComplete(loadedImage);
}
}
});
});
}
imageEvent.init();
totalImage = getTotalImage();
createImageObject();
setOnloadEvent();
count_loaded_image();
};
})( jQuery );
I would like to show my own error image when an image cant load successfully.
I thought of a JavaScript function:
<script type="text/javascript">
var images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
images[i].onerror = onErrorImage(images[i]);
}
function onErrorImage(element){
element.onerror = null;
element.src = 'errorImage.png';
}
</script>
But this doesn't work. This turns every image on the page into my own error image.
Is there another simple way to show my own error image on error?
Or is there another way to bind a function to an event like i did on line 4? Because I'm pretty sure the script fails on that line.
Solution may be in jQuery.
It should be i guess:
images[i].onerror = function(){onErrorImage(this);}
There are a lot of ways to do this, I will show you one of them :
You can make all of your images with "fake-src" and load them when the document is ready. Of course you can make a loader till they are downloading.
Here is a function I write for you:
imagesReady = function () {
var myImgs = document.getElementsByTagName("img");
for (var i = 0; i < myImgs.length; i++) {
getImageReady(myImgs[i]);
};
function getImageReady(el) {
var url = el.getAttribute("src-fake");
var image = document.createElement("img");
image.onload = function() {
el.src = url;
el.style.opacity = 1;
//this image is ok, that why we put his src to be the fake src
};
image.onerror = function (err) {
console.log("err on load :"+image.src);
el.src = url;
//this image fail!
}
image.src = url;
}
}
imagesReady();
I'm trying to display one image in loop. Knowing the path and image-name are okay is this example, how to display one image in loop, and when the image haven't been found, the browser displays the last right image-name until the image-name is found?
#{int j=1;}
<img src="" />
<script>
(function () {
for (var i = 1; true; i++) {
#{ string file = "/MonitoringN/../bitmaps/" + j + ".png"; bool a = System.IO.File.Exists(file) == true; }
var str = "/MonitoringN/../bitmaps/" + i + ".png";
var b = "#a";
if (b)
{
setInterval(function () { $('img').prop('src', str); }, 1000);
} else {
i--;
#{j--;}
}
#{j++;}
}
});
</script>
Because when I execute this code, I get a blank image, and then I can't see the page is loading.
Thanks a lot!
I think I know what you are trying to do ...
If I understand the question correctly, you have a list of images and you want to try to open them until one of them is found. If an image is NOT found, you want to skip to the next one.
First -- I'd simply for your question by separating the Razor stuff and the Javascript off into very separate pieces. In fact, I'm going to skip Razor entirely.
<html>
<head>
<title>A test</title>
</head>
<body>
<img src="http://x.invalid" id="myImage">
<script>
var imgs = [
"http://x1.invalid/none",
"https://www.google.com/images/srpr/logo11w.png",
"http://thedailywtf.com/Resources/Images/Primary/logo.gif"
];
var imageIndex = 0;
function tryNextImage() {
var img = document.getElementById("myImage");
img.onerror = function() {
imageIndex++;
tryNextImage();
}
img.src = imgs[imageIndex];
}
// start the ball rolling
tryNextImage();
</script>
</body>
</html>