How to add alternate text to pictures displayed by clicking on buttons? - javascript

Is there a way to add separate alternate text (such as "picture 1/2 not available") in case a picture fails to display? How can I change this code to allow that to happen?
(Sridhar's code)
<script type = "text/javascript">
function pic1()
{
document.getElementById("img").src = "picture 1 source";
}
function pic2()
{
document.getElementById("img").src ="picture 2 source";
}
</script>
<img src = "" id = "img"/> <input type="button" value="Show Picture
1" onclick="pic1()"/> <input type="button" value="Show Picture 2"
onclick="pic2()"/>

Is there a way to add separate alternate text (such as "picture 1/2
not available") in case a picture fails to display?
Yes, that is what the alt attribute is for - it is actually a required attribute for images anyway.
You can just set the alt tag of an image using .alt like so:
var image = document.getElementById("img");
image.src = "Image src here"
image.alt = "Image alt here - if image failed to render, you will see this!"
Assuming you have to do it by JavaScript. Most people simply just include it in the HTML itself:
<img src = "" id = "img" alt="Alternative text here!"/>
See more about the alt attribute here.
Edit: You could look into using onerror in regard to Derek's point:
"onerror allows for different alt text when an image is simply not found
rendered or when the image is not found"

Yes, there is a way. Use the onerror attribute with the error text or a path to an alternate image.
<img onerror="this.src='/path/to/alternate/img.jpg'" src="/your/img.jpg">
or
<img onerror="this.alt='picture 1/2 not available'" src="/your/img.jpg">
Edit: Of course, you should be using the (required) alt attribute on every image, as Zenith points out. Use of onerror assumes you wanted to show the user something different if the image could not be found instead of, say, the user is using a screen reader or has otherwise chosen to disable images. One alternative is to show the original alt text with the 'not available' message appended:
<img alt="picture 1/2" onerror="this.alt=this.alt+': not available'" src="/your/img.jpg">
Demo

Related

Change image src with event on an other element jquery

I generate procedurally a div containing an image and an input file in an HTML file.
The ID of all the element change by 1 each time. Here is the sample of the div that is repeated with K as the number that is incremented each time I generate this div, so every item has a different ID.
<div>
<img id="frame-add-K" src="" class="img-fluid" />
</div>
<label style="border: 2px solid black" for="img-input-K" class="btn">Select Image</label>
<input type="file" name="image_content_K" id="img-input-K" style="display:none; visibility:hidden;" accept="image/*" />
The div containing the image is supposed to work as a preview. So when the user input his image, I want to change the img source to the newly updated image.
I have tried something like this using jquery:
$(document).ready(function() {
$("input[id^=img-input-]").on("input", function() {
var id_input = $(this).attr('id').substring('img-input-'.length); //get me only the number at the end
$("#frame-add-" + id_input).attr("src", event.target.files[0]);
});
});
But id_input is always egual 1, so the change only affect my first div and change always the first image source. Moreover "event.target.files[0]" doesn't work there.
I ideally would like to make a generic function using jquery that would get the K of the element changed et update the image src associated with this K but I am open to any suggestion solving my issue.
Rather than use any ids, you can select the image which is the child of the div element two before the input.
const theImg = $(this).prev().prev().find("img");

Can't seem to grab alt attribute

I'm trying to grab the "alt" attribute of an image inside "uCW", but nothing's printing.
Here's the image:
<img class="i09qtzwb n7fi1qx3 datstx6m pmk7jnqg j9ispegn kr520xx4 k4urcfbm bixrwtb6" height="261" src="https://external-ort2-2.xx.fbcdn.net/safe_image.php?d=AQAayZaQwp_d10l4&w=750&h=391&url=https%3A%2F%2Fimg.buzzfeed.com%2Fbuzzfeed-static%2Fstatic%2F2020-04%2F28%2F13%2Fasset%2F36517ba3257e%2Fsub-buzz-279-1588079535-1.png%3Fcrop%3D768%3A402%3B0%2C8&cfs=1&ext=jpg&_nc_hash=AQBIX7qpH_aPKJby" width="500" alt="A Reporter Went On "GMA" Wearing No Pants. He Didn't Realize We Could All See.">
(Sorry about the long line, I couldn't figure out how to get it to wrap.)
Here's my code:
var title = $(uCW).find('[src^="https://external"]').attr("alt");
console.log(title);
Nearly identical code works fine for grabbing the URL:
var image = $(uCW).find('[src^="https://external"]').attr("src");
console.log(image);

how to display dynamic <img src> on webpage

i want to make a website that allow users to input questions, and then the website will display some pictures related to user input
i tried to wrap the output in img src tag, however the output is simply a line of code instead of picture
<img src="path/reply.jpg" width="68" height="90" alt="reply">
how can i tell the website to recognize it as a picture and display it ?
is it possible to extend this function to embed youtube video etc. ?
==================================================================
Added some scripts below, i guess this is the code that limiting output as text only.....
function createRow(text) {
var $row = $('<li class="list-group-item"></li>');
$row.text(text);
$chatlog.append($row);
}
Update: i amended $row.text(text); to $row.html(text); , it can properly display html code now.
you can use ParentNode.append() function to append new image element to your html. (documentation here: https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append)
Example:
var yourImage = document.createElement("img");
yourImage.src = "some/dynamic/source.jpg"
document.body.append(yourImage);
It is very simple, just try the following changes:
Add id attribute to your img tag:
<img src="path/reply.jpg" width="68" height="90" alt="reply" id="img1">
And in Jquery:
$(document).ready(function ()
{
$("#img1").attr({ "src": "img.jpg" });
});

Set <img> alt tag with JavaScript

I know how to set an ALT tag on an <img> if I have the class or globally to all the images on the page, however how can I do it to a specific image that doesn't have an id or class? Can I use the parent DIV somehow to reference the image and add an alt tag?
<div id="table_processing">
<img src="processing_report.gif"> Loading Report List...
</div>
I'd recommend using document.querySelector(), which allows you to select the image using CSS (jQuery-like) selectors.
Like this:
var image = document.querySelector("#table_processing img");
and then you can set the alt attribute with:
image.alt = "Our New Alt Text";
or
image.setAttribute("alt", "our New Alt Text");
Here's a demo:
var image = document.querySelector("#table_processing img");
image.alt = "Our New Alt Text";
<div id="table_processing">
<img src="http://via.placeholder.com/350x150"> Loading Report List...
</div>
if you use jQuery, you could use the ID from the parent element like this:
$('#table_processing img').attr('alt', 'your text here');
This "css selector" will get all images inside the div with the id "table_processing" and sets the alt tag.
Pure/True/Real/Faster JavaScript Solution:
function setAlt()
{
var div = document.querySelector("#table-processing");
var image = div.querySelector("img");
image.setAttribute("alt", "something");
}
JQuery allows you to use valid css selector, so you can use this:
$('#table_processing img').attr('alt', <text>);
I hate to keep plugging jQuery, but here is a very good example of automating missing alt tags with generic info, this is something I do to patch for WCAG AA compliance until we can edit all the content.
$("img:not([alt])").attr({ alt: "your alt text", role: "presentation" });
$("iframe:not([title])").attr({ title: "your iframe title" });
This looks for images without alt attributes, adds it and adds the value "your alt text here" along with a role for screen readers, but you can remove that. IO. also do the same for iframes and embeds that may be third parties that are out of compliance.

Render/ Preview Image from URL input

I'm looking for a solution to render image before uploading via input URL.
My code
<input name="thumbnail" placeholder="Post image URL here" />
I've been trying methods like this. Adding onchange="readURL(this);" to above mentioned code does nothing. It appears they only work with local files only.
use the value of the input as the source for an image tag. You can hide and show the image tag, create a new image each time, wait for the load event and show a spinner, use a default image, the possibilities are endless.
$('[name="thumbnail"]').on('change', function() {
$('img.preview').prop('src', this.value);
});
FIDDLE
You could use canvas.
var oCanvas = doc.getElementById('imgThumb'),
oContext = oCanvas.getContext('2d');
oContext.drawImage(this, 0, 0, nWidth, nHeight);
Try out my fiddle http://jsfiddle.net/aliasm2k/tAum2/

Categories