JavaScript continuously executing and then stops - javascript

I created a js file and created a function and what it supposed to do is change the image once everytime my page is loaded..
function swapPic() {
var imgSrc = [];
imgSrc[0] = "/Content/Resources/cafe1.jpg";
imgSrc[1] = "/Content/Resources/cafe2.jpg";
imgSrc[2] = "/Content/Resources/cafe3.jpg";
imgSrc[3] = "/Content/Resources/cafe4.jpg";
imgSrc[4] = "/Content/Resources/cafe5.jpg";
imgSrc[5] = "/Content/Resources/cafe6.jpg";
var randomnumber = Math.floor(Math.random() * 5);
var img = document.getElementById("imgContainer");
img.setAttribute("src", imgSrc[randomnumber]);
// alert("ok");
}
In my html code, in my img tag:
<img id="imgContainer" src="~/Content/Resources/cafe3.jpg" onload="swapPic()"/>
Adding the alert("ok") line and i reload the page once, the alert window keeps popping up and the image changes. I keep closing the window, and it still pop ups and the image changes. It just stopped after some time.
So I guess, during the time i did not include that alert("ok") line, my function is continuously called and stop. It just happen so fast which makes it look like fine.
I think this is a problem. Do you have any idea guys how can I make sure that my function is just called once?

You should add onloadon the body, not the img.
<body onload="swapPic();">
<img id="imgContainer" src="~/Content/Resources/cafe3.jpg"/>
</body>
If you add onload to the img, then the function will be called each time the image is loaded, which causes an infinite loop.
If you cannot modify the body tag, then replace your current function swapPic() with this:
(function swapPic() {
var imgSrc = [];
imgSrc[0] = "/Content/Resources/cafe1.jpg";
imgSrc[1] = "/Content/Resources/cafe2.jpg";
imgSrc[2] = "/Content/Resources/cafe3.jpg";
imgSrc[3] = "/Content/Resources/cafe4.jpg";
imgSrc[4] = "/Content/Resources/cafe5.jpg";
imgSrc[5] = "/Content/Resources/cafe6.jpg";
var randomnumber = Math.floor(Math.random() * 5);
var img = document.getElementById("imgContainer");
img.setAttribute("src", imgSrc[randomnumber]);
// alert("ok");
})();
This will execute it exactly once. No need to call it anywhere.

images have their own load event that refers to when the image finishes loading. so, each time you update the src, the browser of course starts loading the image, and fires the event again once it finishes loading it. the cycle repeats.
You could use window.onload to call your function just once, because the window's load event can only happen once.

You've attached onload to an image. In this case swapPic() will be called on every image load. So, what happens is an endless loop - you call swapPic(), it loads a new image which triggers again swapPic(). For more information look at W3Schools: Event - Img Onload.
You should move the swapPic() to body. This will trigger swapPic() only when the body is loaded.
Another way is to use javascript:
// if you have jQuery
$(document).ready(function(){
swapPic()
});
// ordinary javascript
window.onload = function() {
swapPic();
}

Use the onload function in tab. BTW according to your code your imgSrc[5] = "/Content/Resources/cafe6.jpg"; will never be shown as your random function only generates 0-4.
it should be
var randomnumber = Math.floor(Math.random() * 6);

Related

Why my var is null and the code doesn't work

I'm starting with the basics in JS and I try to make my first event, change the image if it clicked but it's not working, where's the prob?
let myImage = document.querySelector('img');
myImage.onclick = function() {
let mySrc = myImage.getAttribute('src');
if(mySrc === 'images/coding_icon.png') {
myImage.setAttribute ('src','images/coding2.png');
} else {
myImage.setAttribute ('src','images/coding_icon.png');
}
}
My var myImage return NULL and nothing happen when I click on my image. It seems that the doc...selector don't select the first occur of img. Sorry if I did something wrong with the post, it's my first time posting here.
Thanks
You are probably using querySelector on img before it really loaded into DOM.
Possible solutions:
1) move your script in the body tag after the img tag declaration.
2) use code on event of other tags, for e.g. on a button click
3) you can put a timeout surrounding script so that it run delayed and DOM can be loaded meanwhile

Javascript: Append and Remove Image from a DIV in setTimeout loop

I'm trying to load an image into a div using JavaScript. Below is the current snippet of the code.
window.onload=function image_show() {
var thumbContainer = document.getElementById("art_img");
var thumbnail = document.createElement("img");
var img_width = document.getElementById("art_img").offsetWidth;
var img_height = document.getElementById("art_img").offsetHeight;
thumbnail.onload=function() {
thumbContainer.appendChild(thumbnail);
}
thumbnail.src = "http://xyz/bkg.png";
thumbnail.width = img_width;
thumbnail.height = img_height;
setTimeout(image_show, 1000 );
}
The appendChild() method keeps appending the images (one below the other) after the Timeout. But I want to actually keep refreshing the div with the same image.
The source of the image will be updated on my website with the same name, and I want the script to display the new image after Timeout. I tried inserting a removeChild() method just before appendChild(), but didn't work as expected. Any help will be appreciated.
just empty the element before you append again
thumbnail.onload=function() {
thumbContainer.innerHTML = ""; // ADD THIS LINE
thumbContainer.appendChild(thumbnail);
}
The problem is that the browser caches the image.
Try appending a timestamp to the src attribute of the thumbnail:
thumbnail.src = "http://xyz/bkg.png?ts=" + Date.now();
This way, the source URL will be slightly different each time the image_show function runs and the picture should be loaded by the browser each time.

Perform image analysis only after images are already loaded

I am looking for a way to scale images of a web page for mobile devices. My approach is to store the dimensions of each image using JavaScript, and if the screen of the user is smaller than a certain value, all images will be resized using JavaScript. My problem is that the following function does not detect if the images are already loaded, so the result would be 0 for not loaded images. My question is, how can I implement a check, so that the function will compute the image size only after the image was completely loaded? I am not using jQuery.
function storeImageSizes() {
isizes = [];
imgs = document.getElementById('content').getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
isizes[i] = [
window.getComputedStyle(imgs[i]).getPropertyValue('width').replace('px', '') * 1,
window.getComputedStyle(imgs[i]).getPropertyValue('height').replace('px', '') * 1
];
}
}
Add a listener to be called when all DOM elements load. ie:
document.addEventListener("load", (function(){
isizes = [];
imgs = document.getElementById('content').getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
isizes[i] = [
window.getComputedStyle(imgs[i]).getPropertyValue('width').replace('px', '') * 1,
window.getComputedStyle(imgs[i]).getPropertyValue('height').replace('px', '') * 1
];
}
})
Did you try image.onload?
Also, check this answer out. It highlights the use of image.onload and also avoids browser cache issues.
You can use the following solution to perform image analysis after the images are already loaded:
document.querySelector('#image').addEventListener('load', storeImageSizes);
Calling storeImageSizes() in window.load function should fix the problem
$( window ).on( "load", function() { ... })
It basically is an event which is triggered when all the images and the complete page is loaded. Since you want the function to run when all the images are loaded you should use this event.
Note the difference between document.ready and window.load.
document.ready runs when the DOM is ready where as window.load runs once the complete page is loaded i.e., images/iframes etc.
Take reference from here Simple example using Jquery

Only run function on button press

I have a script which checks for an image and then loads a page if it has been found.
I am trying to attach the function to a button so that it only checks when the button is pressed rather than on page load.
<input type="button" id="ImgLoad" value="Check connection">
At the moment, the page redirects on load and is not attached to the button press. I'm struggling to see where I've gone wrong with it.
<script>
networkdelay = window.setTimeout(function()
{window.onclick=encaseimage()}, 1000);
</script>
<script>
clickdelay = window.setTimeout(function(){window.onclick=autoc()},
1000);
</script>
<script>
function encaseimage(){
function ImgLoad(myobj){
var randomNum = Date.now() || new Date().getTime();
var oImg=new Image;
oImg.src="http://192.168.8.1/images/ping2.jpg"+"?rand="+randomNum;
oImg.onload=function(){window.location.href = "/status.html";}
}
networkchecker = window.setInterval(function()
{window.onclick=ImgLoad()},1000);
}
</script>
You are calling the function instead passing the function reference:
window.onclick=ImgLoad()
Should be:
window.onclick=ImgLoad
Otherwise the ImgLoad function runs immediately.
I should say that adding onclick to window is probably not the best design (depending on what you are doing). Usually, you would look up the button (by id perhaps) and attach a click handler only to that particular button.
On a side note, it looks like the other window.onclick events are also setting to the result of calling a function:
window.onclick=encaseimage()}, 1000);
window.setTimeout(function(){window.onclick=autoc()},
You may want to review those as well. :)
If you want to load image on button click you need to attach that to the button click event.
like
$("#ImgLoad").click(function(){
var randomNum = Date.now() || new Date().getTime();
var oImg=new Image;
oImg.src="http://192.168.8.1/images/ping2.jpg"+"?rand="+randomNum;
oImg.onload=function(){window.location.href = "/status.html";}
});

Javascript/JQuery - How can I reset onError function for broken images? (for a second broken image)

OK, I've got the onError javascript working nicely. However, in most cases I need to try an alternate image and if THAT is broken as well, it needs to fall back to a local default image.
On the initial broken image (http://somesite.com/someimage.jpg), this code correctly loads the alternate image that is passed. However, as you can see from the code, I'm trying to reset the source.onerror so that if the alternate image is broken as well, it will just load the local default image (/some/local/file.jpg). However, defaultImage() is never called. It's not a matter of passing in the "this" either because if I change it to source.onerror="alert('hi')"; it never gets called anyway.
It appears that when the page loads, it only kicks of onerror once and never tries it again. Is there some way I can force the DOM to try loading the img again so that the new onerror function will kick off if the alternate image is broken?
<img src="http://somesite.com/someimage.jpg" onerror="AltImage(this, 'http://sommesite.com/otherimage.jpg');"/>
<img src="http://somesite.com/someimage.jpg" onerror="AltImage(this, '');"/>
<script>
function AltImage(source, alt_image){
if (alt_image !=""){
source.src = alt_image;
source.onerror = "defaultImage(this)";
return true;
}
source.src = "/some/local/file.jpg";
source.onerror = "";
return true;
}
function defaultImage(source) {
source.src = "/some/local/file.jpg";
data.onerror="";
return true;
}
</script>
You can check if the image exists or not by using the function below instead of your method :
function ImgLoad(myobj,sSrc)
{
var oImg=new Image();
oImg.src="http://mydomain.com/images/"+sSrc;
oImg.onload=function(){myobj.src=oImg.src}
oImg.onerror=function(){myobj.src="http://mydomain2.com/images/"+sSrc}
}
What I would try to do:
$(function() {
$('img.fallbackable').error(function() {
$(this).unbind('error');
this.onerror = function() {
this.src = 'default.png';
};
this.src = $(this).data('altsrc');
})
.attr('src', function() {
return $(this).data('src');
});
});
And in HTML define your images which should have desired behaviour the next way:
<img data-src="someimage.jpg" data-altsrc="otherimage.jpg" class="fallbackable">
So images start loading not immediately but only when the DOM is ready and all these image objects have onerror handler attached. Thus we make sure that for all such images (which is marked with class fallbackable) there is an error handler to be executed if needed.

Categories

Resources