Hide img when alternate image not exists - javascript

In asp.net img tag I need to set gif image. I set gif image for src of the img and if gif doesn't exist I need to set jpg for the img. But if the jpg also not exists I need to hide the img from the page.
I used onerror event of the img tag for this with the javascript function. But at sometimes it saying the function not found.
Is there ay easy way to do this. My need is to set gif to img and if the gif not exists set jpg to it and if jpg also not exists need to hide the img.
I tried like this
<img src="mygif.gif" onerror="setJpg($(this));">
function setJpg(source) {
var file = source[0].src;
var jpgFile = file.substr(0, file.lastIndexOf(".")) + ".jpg";
var img = document.createElement('img');// new Image();
img.onload = function () { source[0].src = jpgFile; };
img.onerror = function () { source.parent().hide() };
img.src = jpgFile;
}

The onerror event eventually gets recalled after changing the src of the image. So you do not have to create another img and can resue the same event. Like set a new handler or check for the ending.
//REM: Note that "img" is an element and not jquery wrapped.
function setJpg(img){
console.log('Called onerror');
//REM: If image ends with ".gif"
if(img.src.toLowerCase().endsWith('.gif')){
//REM: Change ".gif" to ".jpg", whatever your logic is.
//REM: This is going to call onerror again if not found
img.src = img.src.replace('.gif', '.jpg');
console.log('Changed src', img.src)
}
else{
//REM: Remove the event
img.onerror = null;
//REM: Remove the image or do whatever you want with it
img.remove();
console.log('Removed element')
}
}
<img src = 'wayne.gif' onerror = 'setJpg(this)'>

Related

Image Swap on MouseOut (JavaScript, not JQ)

I am trying to create functions to mouseover and mouseout of images. The tricky part is this function needs to work for any image, and I cannot use direct image names. I have to therefore use variables.
The HTML code is as follows for the images:
The HTML for the images is like this, and there are 3 images:
<img src="images/h1.jpg" alt="" id="images/h4.jpg" onmouseover="swapToNewImage(this)" onmouseout="swapImageBack(this)">
I'm expecting that you have to reference the id for the new image, and then the src attribute for the previous image to revert when you mouseout.
The problem is that, if I reference the id attribute, the image no longer has information on the src attribute so I cannot call it to revert back.
Here is the JavaScript I have thus far. It works to swap the image to a new one, but not to swap it back :(
//FUNCTION
var $ = function (id) {
return document.getElementById(id);
}
//ONLOAD EVENT HANDLER
window.onload = function () {
//GET ALL IMG TAGS
var ulTree = $("image_rollovers");
var imgElements = ulTree.getElementsByTagName("img");
//PROCESS EACH IMAGE
//1. GET IMG TAG
for (var i = 0; i < imgElements.length; i++) {
console.log (imgElements[i]);
console.log (imgElements[i].getAttribute("src"));
//2. PRELOAD IMAGE FROM IMG TAG
var image = new Image();
image.setAttribute("src", imgElements[i].getAttribute("src"));
//3. Mouseover and Mouseout Functions Called
image.addEventListener("mouseover", swapToNewImage);
image.addEventListener("mouseout", swapImageBack);
}
}
//MOUSE EVENT FUNCTIONS
var swapToNewImage = function(img) {
var secondImage = img.getAttribute("id", "src");
img.src = secondImage;
}
var swapImageBack = function(img) {
var previousImage = img.getAttribute("src");
img.src = previousImage;
}
Let me know if you can help me figure out how to call the image's src attribute so it can be reverted back. Again, I cannot reference specific image names, because that would be a lot easier (: Thank you!
Well, You can use a data attribute to store your src, and a data attribute to store the image you want to swap when mouseover.
Please try the following example.
var swapToNewImage = function(img) {
var secondImage = img.dataset.swapSrc
img.src = secondImage;
}
var swapImageBack = function(img) {
var previousImage = img.dataset.src
img.src = previousImage;
}
<img src="https://images.pexels.com/photos/259803/pexels-photo-259803.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="" data-src="https://images.pexels.com/photos/259803/pexels-photo-259803.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" data-swap-src="https://images.pexels.com/photos/416160/pexels-photo-416160.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" onmouseover="swapToNewImage(this)" onmouseout="swapImageBack(this)">
I also notice that the image tag is generated by code, in order to set the dataset values, we can do this:
var image = new Image();
image.scr = [src]
image.dataset.src = [src]
image.dataset.swapSrc = [swap src]

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.

How to get ALT from IMG tag in JavaScript

I am using THIS script to display my galleries in lightbox. I was using some plugins but all of them does not display the alt=""(alt added in media in wordpress).
How can I modify the code from the link below to display the alt attributes ?
I found something in the code, but I dont know how to put the dynamic alt there(commented by uppercase text in the code). Dynamic I mean that as user will add the img in wordpress dashboard, he will put the alt then.
{
key: '_preloadImage',
value: function _preloadImage(src, $containerForImage) {
var _this4 = this;
$containerForImage = $containerForImage || false;
var img = new Image();
if ($containerForImage) {
(function () {
// if loading takes > 200ms show a loader
var loadingTimeout = setTimeout(function () {
$containerForImage.append(_this4._config.loadingMessage);
}, 200);
img.onload = function () {
if (loadingTimeout) clearTimeout(loadingTimeout);
loadingTimeout = null;
var image = $('<img />');
image.attr('src', img.src);
image.addClass('img-fluid');
image.attr('alt',"Temp TEXT"); // HERE I WOULD LIKE TO DISPLAY THE ALT AUTOMATICALLY - NOT STATIC AS IT IS NOW
// backward compatibility for bootstrap v3
image.css('width', '100%');
$containerForImage.html(image);
if (_this4._$modalArrows) _this4._$modalArrows.css('display', ''); // remove display to default to css property
_this4._resize(img.width, img.height);
_this4._toggleLoading(false);
return _this4._config.onContentLoaded.call(_this4);
};
img.onerror = function () {
_this4._toggleLoading(false);
return _this4._error(_this4._config.strings.fail + (' ' + src));
};
})();
}
img.src = src;
return img;
}
},
I am using wordpress on my page and my skills in JS are rather poor, so I am asking you :).
We don't really know what is the type of your img variable. If you want to set the alt tag of image to the one of img, simply do:
image.attr('alt', img.attr('alt'));
…if it's a jQuery object. Otherwise, if img is pure JavaScript, you can do:
image.attr('alt', img.alt);
if the img object holds the existing alt and image is the new jQuery object, then set it with jQuery
image.attr('alt', img.getAttribute('alt'))

Attempting to change an image onclick via PHP/Javascript/HTML

I've looked at numerous other answers regarding this but haven't found a solution that has worked. I'm using a PHP page that contains some HTML code, with Javascript working some functions. Ideally I would select an image on the page, the image will become colored green as it is selected. I would then like to deselect the image and have it return to the original state. I can only get half-way there however. What am I missing? Is it something with post back?
Here's some code examples:
The HTML:<div onclick="changeImage(1)" id="toolDiv1"><img id="imgCh1" src="/images/Tooling/1.png"></div>
The Javascript function:
function changeImage(var i){
var img = document.getElementById("imgCh" + i + ".png");
if (img.src === "images/Tooling/" + i + ".png"){
img.src = "images/Tooling/" + i + "c.png";
}
else
{
img.src = "images/Tooling/" + i + ".png";
}
}`
The "1c.png" image is the one that is selected and should replace "1.png". There are multiple divs on this page that hold multiple images, which are named 2/2c, 3/3c, which is why the var i is included. Any insight? Thanks in advance.
You could do it something like this, it would also allow for different file names.
<img class="selectable" src="/images/Tooling/1.png"
data-original-source="/images/Tooling/1.png"
data-selected-source="/images/Tooling/1c.png">
<img class="selectable" src="/images/Tooling/2.png"
data-original-source="/images/Tooling/2.png"
data-selected-source="/images/Tooling/2c.png">
 
var images = document.getElementsByClassName('selectable');
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
function selectElementHandler(event) {
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
image.setAttribute('src', newSrc);
}
 
With comments:
// find all images with class "selectable"
var images = document.getElementsByClassName('selectable');
// add an event listener to each image that on click runs the "selectElementHandler" function
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
// the handler receives the event from the listener
function selectElementHandler(event) {
// the event contains lots of data, but we're only interested in which element was clicked (event.target)
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
// if the current src is the original one, set to selected
// if not we assume the current src is the selected one
// and we reset it to the original src
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
// actually set the new src for the image
image.setAttribute('src', newSrc);
}
Your problem is that javascript is returning the full path of the src (you can try alert(img.src); to verify this).
You could look up how to parse a file path to get the file name in javascript, if you want the most robust solution.
However, if you're sure that all your images will end in 'c.png', you could check for those last 5 characters, using a substring of the last 5 characters:
function changeImage(var i){
var img = document.getElementById("imgCh" + i);
if (img.src.substring(img.src.length - 5) === "c.png"){
img.src = "images/Tooling/" + i + ".png";
}
else
{
img.src = "images/Tooling/" + i + "c.png";
}
}

Problem with image() object

Look at this script please
var src="some.jpg";
var img = new Image();
img.src = src;
img.id = "crop_image";
$("#crop_image").load(function()
{
$("#crop_cont").append(img);
})
why in my .load function i can't access to img element?
Thanks much
UPDATE:
But the following works
$('<img src="'+src+'" />').load(function()
{
var img = new Image();
img.src = src;
$("#crop_cont").append(img);
})
Neither of those two examples really make any sense.
In the first, you create an Image but you don't add it to the DOM. Thus, when you ask jQuery to go find it, it can't because it's not there yet.
In the second, you create a new image tag, which (internally) is going to give jQuery an actual DOM element to work with. However, that call to append your Image object to the DOM seems superfluous. You've already got an <img> so there's no need for another one.
I'd change the second one as follows:
$('<img src="'+src+'" />').load(function() {
$("#crop_cont").append(this);
});
$("#crop_image") will not find your new image because you haven't added it to the DOM yet. Use $(img) instead.
A correct way to do it would be:
var src="some.jpg";
var img = new Image();
img.src = src;
img.id = "crop_image";
$(img).load(function(){
$("#crop_cont").append(this);
});
#crop_image, does it actually get appended to the doc? if so when?
you need to provide html to that.right
<img src="" />
Otherwise how can it display
image has it's own onload event, it's probably easiest to do something like this
var src="some.jpg";
var img = new Image();
img.id = "crop_image";
img.onload = $("#crop_cont").append(img); // event added
img.src = src;
edit: err, I mean the Image Object.

Categories

Resources