how to load images after everything else is loaded? - javascript

i got some idea that to load a fake image on a div before original image finishies loading and that to be after winodws load.i got some code but cant understand in which part i have to put src image for fake image and original image.do help me out in this code .
my html part is
<div class="myimage"><img src="myimage.jpg" /></div>
note:Trick is to set the src attribute only when that source is loaded in temporary img. $(img).load(fn); handles that.
$(function(){
$.each(document.images, function(){
var this_image = this;
var src = $(this_image).attr('src') || '' ;
if(!src.length > 0){
//this_image.src = options.loading; // show loading........
var lsrc = $(this_image).attr('lsrc') || '' ;
if(lsrc.length > 0){
var img = new Image();
img.src = lsrc;
$(img).load(function() {
this_image.src = this.src;
});
}
}
});
});

You can use data attribute to do it:
<div class="myimage"><img data-orig="original.jpg" src="fake.jpg" /></div>
$(window).load(function(){
$('.myimage img').attr("src", $(this).data('orig')).removeAttr('data-orig');
});

You can add your images url to a custom data-url attribute and make your image url a base64 1x1 gif. And then when the page loads completely you can get your url from it. Basically it will be like this.
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="original-image.png" />
$(window).load(function() {
$("img").each(function() {
$(this).attr("src", $(this).attr("data-src"));
});
});

Related

How to set img src dynamically with a function

I want to set img src=" " with a function in javascript that changes the picture upon a variable and checks values:
javascript file code:
function myFunctionstatus(){
var ledactual=document.getElementById("ledonof").value
var image = document.getElementById('ledPic');
if (ledactual==ledon) {
image.src = "https://cdncontribute.geeksforgeeks.org/wp-c
content/uploads/OFFbulb.jpg";
}
if (ledactual==ledoff){
image.src = "https://cdncontribute.geeksforgeeks.org/wp-
content/uploads/ONbulb.jpg";
}
} };
img src in html file:
<img id="ledPic" [src]="myFunctionstatus()" >
but it didn't work with me and the picture didn't appear! the script is working, I tested with a button:
<input type="button" id="ledonof" onclick="myFunction();myFunctionstatus();" class="ledonoff" value="<?phpinclude ('ledstatus.php'); ?>">
how can I set img src with a function?
I can't comment on the php that you're using to get the status, but the below is a working javascript example:
function myFunctionstatus(){
var input = document.getElementById("ledonof");
var image = document.getElementById('ledPic');
if (input.value == "on") {
image.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/ONbulb.jpg";
input.value = "off"
} else if (input.value == "off"){
image.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg";
input.value = "on"
}
}
myFunctionstatus()
<img id="ledPic" />
<input type="button" id="ledonof" onclick="myFunctionstatus();" class="ledonoff" value="on">
As noted by others, src doesn't support function calls (and you don't even return anything from your function call), so you need to run the function once at the start to set the image to the initial status.
You need to set an initial state manually
function switchStatus() {
let switchButton = document.getElementById('ledonof');
let img = document.getElementById('ledPic');
if(switchButton.value == "ledon") {
img.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg";
switchButton.value = "ledoff";
} else {
img.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/ONbulb.jpg";
switchButton.value = "ledon";
}
}
<img id="ledPic" src="https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg" > <input type="button" id="ledonof" onclick="switchStatus();" value="ledoff">
img src attr does not support function call. Whatever you pass in the src will be considered as url(relative or otherwise).
Please refer https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#Attributes
So what you need to do is call the function before/loading your element and change the src then. The simplest form would be following
`<script>
(function() {
// your page initialization code here
// the DOM will be available here
// call the function here
})();
</script>`
You can't do this. The src attribute of an image element can't be interpreted as javascript when the HTML is interpreted.
initially, you need to set src, and on button click, you can toggle image by changing image src.

Trying to change the src of an image using sessionStorage

I have 2 html pages with an image on each one. I need to be able to click the image on the 2nd page and have it redirect me to the 1st page - with the first image.src changed to that of the second.
What is the best/correct way to do this? I have been trying to do it by storing the src in sessionStorage but it does't seem to be working. Here is the code for setItem:
<script type="text/javascript">
$('.images').on('click', '.groupOne', function(){
var image = $(this).find("img"); // selects images inside group
var imageSrc = img.first().attr("src"); // get src of first image
sessionStorage.setItem("choice", imageSrc);
window.location.href = 'firstPage.html';
});
</script>
And then to change the first image I need to use getItem:
<script type="text/javascript">
$(document).ready(function() {
var imgTwo = sessionStorage.getItem("choice");
var imgOne = document.getElementById("pageOneImage");
imgOne.src = imgTwo; //sets src of img1 to src of img2
});
</script>
But this doesn't seem to be working. Is there an easier way to do this using more jQuery? Thank you!
Maybe not the best solution, but how about adding the src as a param to the query string?
On the second page:
window.location.href = 'firstPage.html?src=' + src;
And the first page:
var reg = new RegExp("(^|&)src=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
var src = r != null ? unescape(r[2]) : null;
Now you got the src, if redirecting from the second page.

To display image using JavaScript

In the code below I have an image in C Directory and I want to display the image on window load using JavaScript. I tried but image is not displaying.
<div id="thmbDiv"></div>
Script:
window.onload=function() {
var thumbContainer = document.getElementById("thmbDiv");
var thumbnail = document.createElement("img");
thumbnail.onload=function() {
thumbContainer.appendChild(thumbnail);
}
thumbnail.src = "C:\Hello\Search\Image0529.jpg";
}
Try
<div id="thmbDiv"><img id="imageTag" src=""></div>
window.onload=function() {
var thumbnail = document.getElementById("imageTag");
thumbnail.src="C:\Hello\Search\Image0529.jpg";
}

Condition to display image in Javascript

I'm looking for create a small javascript code to display images if their src is valid.
I have to separate the script to the html page for better organisation.
Here is what I did :
HTML
<img id="thmb" src= "http://blog.lefigaro.fr/bd/img-sanctuaire.png" width="50px" height="50px" alt="" ;>
JavaScript
var thumbnail = document.images.thmb;
if(thumbnail.src)
{
if(thumbnail.onerror)
{
thumbnail.src = "http://blog.lefigaro.fr/bd/img-sanctuaire.png";
}
}
else
{
thumbnail.style.display = "none";
}
Bu it doesn't work, when I empty the src code in HTML, the border of the image still in the page. And if I write a wrong URL, we can't see the image set in the JavaScript.
Here is the JSFiddle to experiment it.
http://jsfiddle.net/gUb8X/
I'm a beginner in JavaScript.
Thank you !
You are too late with the test.
Try this
Live Demo
window.onload=function() {
var thumbContainer = document.getElementById("thmbDiv");
var thumbnail = document.createElement("img");
thumbnail.onload=function() {
thumbContainer.appendChild(thumbnail);
}
thumbnail.src = "http://blog.lefigaro.fr/bd/img-sanctuaire.png";
}
Now replace your image with a div with id thmbDiv
if you put placeholders or hide all images you want to test, you can get the src from a data attribute.
Live Demo
window.onload=function() {
var imgs = document.images; // or document.getElementsByClassName("testImage");
for (var i=0, n=imgs.length;i<n;i++) {
var theImage = imgs[i];
var src = theImage.getAttribute("data-src");
if (src) {
theImage.onerror=function() {
this.style.display="none"; // or this.parentNode.removeChild(this);
}
}
theImage.src=src;
}
}
A neat inline solution would be this
DEMO http://jsfiddle.net/LstNS/25/
<img src="rando/path" id="image" onerror="this.style.display='none';"/>
jQuery:
You can use an ajax call to check if the image file exists
$.ajax({
url:'http://yourhost/someimage.ext',
type:'HEAD',
error: function()
{
//file does not exist
},
success: function()
{
//file exists do something here
}
});
DEMO http://jsfiddle.net/LstNS/24/
As you can see in the demo, the second image is not loaded and presented as a broken image as it does not exist.
A non jQuery version would be
var img = document.getElementById("myImg");
img.onerror = function () {
this.style.display = "none";
}
Your code now tests for thumbnail.src, which means that you are testing for the existence of an src propery, which always exists for a syntactically valid img element. Then you test for the existence of an onerror event handler, and since there is none, you take a branch that does nothing.
A way that works is to use an onerror attribute in the img element and make it remove the element (or remove it from rendering, but actually removing the element is more logical, and safer):
<img id="thmb" src= "http://blog.lefigaro.fr/bd/img-sanctuaire.png"
width="50" height="50" alt="" onerror="rm(this)">
<script>
function rm(elem) {
elem.parentNode.removeChild(elem); }
</script>
Unfortunately, you can’t do this so with a loop that traverses through all img elements. If you try that, your code will run only after the image loading has been performed, so it would be too late to try to set onerror handlers on them.
I just found a little trick to make it possible. That doesn't follow the convention but it works. I just use the "alt" image keyword as the "src" keyword, and the JavaScript gives the src equals to alt attribute found in the html.
<img id="thmb" width="50px" height="50px" alt="http://blog.lefigaro.fr/bd/img-sanctuaire.png" ;>
Javascript :
var img = document.getElementById("thmb");
img.src= img.alt;
img.onerror = function () {
img.style.display = "none";
}
http://jsfiddle.net/LstNS/28/
To more, because I have to use a function to return all the final html code, I did this :
display: function (data) {
var pid = data.record.project_id;
var thb = data.record.Thumbnail;
var base_url = "<?php echo base_url('project');?>/";
function checkImg(){
try
{
var thumbnail = document.createElement("img");
thumbnail.src = thb;
} catch(err) {
//
}
if(thumbnail.height > 0){
var result = 'src="' + thb + '"';
}
else
{
var result = 'style="display:none;"';
}
return result;
}
return '<img id="thumbnail" ' + checkImg() + '" width="50px" height="50px" >';
}
I have to thank you for all your answers which permit me to find a good way to do it !
If you have comments to do, don't hesitate ! ;)

How to replace all empty <img src=""> on a page with JavaScript on dom loaded?

I need a function, that starts, when the DOM is loaded.
In my HTML Page are several empty Image Tags, like and I want to add an Image-Name into the src-property when everything is loaded to get something like
<img src="blank.jpg">.
Best wishes
Chris
Construction <img src=""> is invalid. Never use it.
It's invalid because empty url means url to current page. But current page is HTML document, not image. Browser can make another query of current page and try to use it as image (see this page).
function replaceSrc()
{
var images = document.getElementsByTagName('img');
for(var i = 0; i < images.length; i++)
{
var img = images[i];
if(img.src.length == 0)
{
img.src = 'blank.jpg';
}
}
}
window.onload = replaceSrc;
OR if you want to add more than one handler for the event:
document.addEventListener('load', replaceSrc, false) //W3C
document.attachEvent('onload', replaceSrc); //IE
With jQuery
$(document)
.ready(function() { $('img')
.filter(function(){ return this.src.length == 0 })
.each(function () { this.src = 'blank.jpg'}) });
EDIT:
I realized that you probably want to set the src property before the images load so I changed the code to fire on the document's load event, which happens before the images start loading.
Use jQuery! It's easy.
$('img').attr('src','new-image-name.jpg')
This will set the src attribute of every img tag to 'new-image-name.jpg'.
With jQuery, this would set the src attribute of all img elements with a blank src attribute to "blank.jpg" on page load.
$.ready(function() {
$("img[src='']").attr("src", "blank.jpg");
});
You can use this script.
# Script AddImage.txt
var string pagefile, image, html
# Read in the page file.
cat $pagefile > $html
# Replace all instances of "<img src="blank.jpg">" with the specified image.
while ( { sen -r -c "^<img src=&\>^" $html } > 0 )
sal -r -c "^<img src=&\>^" ("<img src=\""+$image+"\">") $html > null
# Write page back.
echo $html > { echo $pagefile }
Script is in biterscripting. Save the script in file "C:/Scripts/AddImage.txt", run it with this command.
script "C:/Scripts/AddImage.txt" pagefile("/path/to/page.html") image("blank.jpg")
It will replace previous image with "blank.jpg".
With JQuery you can simply solve your problem using following code.
$(function(){
$("img[src='']").attr("src", "blank.jpg");
});
Replace images if null from API data using dom manipulation
const images = document.getElementsByTagName('img');
for(const img of images){
const src = img.getAttribute('src');
if(src === "null" && strGender === "Male"){
img.src = "img/placeholder-male.jpg";
} else if(src === "null" && strGender === "Female"){
img.src = "img/placeholder-female.jpg"
}
}

Categories

Resources