Condition to display image in Javascript - 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 ! ;)

Related

Is there a way to switch images src back to original after on.click src change event?

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.

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.

open if bracket in javascript

I'm trying to execute a HTML code if there is variable in JS, is there something like in PHP, where you can use
<?php
if ($variable == True) { ?>
<img src="image.jpg">
<?php } else { ?>
<img src="image2.jpg">
<?php } ?>
so in JS
<script>
if (variable == true) {
</script>
<img src="image.jpg">
<script>
} else {
</script>
<img src="image2.jpg">
<script>
}
</script>
or it has to been done like this
<script>
if (variable == true) {
$("#element").prepend("<img src='image.jpg'>");
} else {
$("#element").prepend("<img src='image2.jpg'>");
};
</script>
Problem is if I use prepend or innerHTML to insert my "image" that function which is called after click to the image - image.addEventListener('click', function() stop work :/
Thank you :)
Well last one is correct one but you can simplify it:
var src = variable === true ? "image" : "imgage2";
$("#element").prepend('<img src="'+ src +'.jpg">');
Problem is if I use prepend or innerHTML to insert my "image" that function which is called after click to the image - image.addEventListener('click', function() stop work :/
That could be because of dynamically element's creation, you can sort it out with event delegation.
With jQuery:
$('#element').on('click', 'img', function(e){
// put code here
});
With javascript it is little bit different, .querySelectorAll() returns a collection with is array like object, so iteration needs to be there, Collection.forEach(cb) can be used to bind the event:
var imgs = document.querySelectorAll('#element img');
Array.forEach.call(imgs, function(img){
img.addEventListener('click', function(){
// put code here
});
});
And with js all the events are delegated events.
I assume that you want to check if your variable is boolean and you want to check if it is true.
Also i assume that you have several images and you want to prepend new one to them, then you could do:
Create hidden div on the page, Something like this:
<div id="htmlToDomCreator" style="position: absolute; top: 0; left: 0; width: 1px; height: 1px; visibility: hidden;" >
</div>
Inside your javascript code do something like this:
<script>
var htmlToDomCreator = document.getElementById('htmlToDomCreator');
var yourElement = document.getElementById('element');
var htmlTag = "";
if (variable == true) {
htmlTag ="<img src='image.jpg'>";
} else {
htmlTag ="<img src='image2.jpg'>";
}
htmlToDomCreator.innerHTML = htmlTag;
var myImgTag = htmlToDomCreator.firstChild;
if(yourElement.firstChild){
yourElement.insertBefore(myImgTag, yourElement.firstChild);
}else{
yourElement.appendChild(myImgTag);
}
myImgTag.onclick = function() {
// do click stuff here
};
</script>
The idea is that whether you use innerHTML or prepending string with jquery,
you have to take whole innerHTML, prepend string to it and then reinsert
whole content again. As you undoubtedly can see, this "kills" all handlers
added from javascript and you have to reattach them again.
To avoid this, we create dom from string "somewhere else" and then prepend it as a dom child element.
Try this:
<script>
if (variable == true) {
$("#element").attr('src', 'image.jpg');
} else {
$("#element").attr('src', 'image2.jpg');
};
</script>
Comment:This will only change the picture attribute, not the entire <img... /> element. So, events attached to the img element will be preserved.

how to load images after everything else is loaded?

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"));
});
});

Javascript image src on click of image

I'm trying to create a simple image swapper. So I have 20 images on the page, and 1 large one. I want the user to click one of the smaller images from the 20 and it be output into the place of the big image source.
I've only just started but even so my code doesn't seem to validate as the script fails before it even gets to the console.log. Also not sure if I'm using thisID correctly.
<img id='avatar-output' onclick='selectAvatar(thisID)' src='images/avatars/$number.png' />
<script>
function selectAvatar(thisID){
var imageSource = document.getElementById ("avatar-output").src;
console.log("Avatar source is " imageSource);
}
</script>
HTML:
<img id='avatar-output' src='images/avatars/$number.png' />
<img class='avatar-small' src='images/avatars/1.png' />
<img class='avatar-small' src='images/avatars/2.png' />
<img class='avatar-small' src='images/avatars/3.png' />
JS:
var els = document.getElementsByClassName('avatar-small'),
target = document.getElementById("avatar-output"),
handler = function() { target.src = this.src; };
for (var i=0; i<els.length; ++i) els[i].onclick = handler;
Demo
Or, if all small images are together, better use event delegation:
var target = document.getElementById("avatar-output");
document.getElementById("avatar-small-wrapper").onclick = function(e) {
if(e.target.tagName.toLowerCase() === 'img') target.src = e.target.src;
};
Demo
Notes
Better separation of content (html) and behavior (inline JS)
<script> element needs type="text/javascript" attribute
Avoid running JavaScript in global scope to avoid creating global variables, polluting window. Run in in a closure: (function(){ /* code here */ })()
You have a typo in it, change
var imageSource = document.getElementById ("avatar-output").src;
to
var imageSource = document.getElementById("avatar-output").src;
since there is a space where it shouldn't be.
Edit: oh and another one in the
console.log("Avatar source is " imageSource);
line. Add a + between your string and your variable like this:
console.log("Avatar source is " + imageSource);

Categories

Resources