How do I replace only part of an image source? - javascript

Is there a way to use jQuery to change a part of an image's source URL?
I'm working on a page that has a number of image elements that are all programmatically generated (but I'm not able to access the source code that generates them). And they all share the same class.
Let's say I have the following HTML:
<img src="https://cdn.example.com/pictures/01.jpg" class="photo">
<img src="https://cdn.example.com/pictures/02.jpg" class="photo">
<img src="https://cdn.example.com/pictures/03.jpg" class="photo">
<img src="https://cdn.example.com/pictures/04.jpg" class="photo">
Simple enough. But now, what if I want to point them all to a different directory? Like: /images/
So far, I've tried a few things, including this bit of jQuery, but nothing's done the trick so far:
$("img.photo").attr("src").replace("pictures","images");
That feels like it should do it because it's targeting images with that class -> then the "src" attribute -> and telling it to replace "pictures" with "images."
But I'm extremely new to using jQuery, so I'd appreciate some help.
What am I missing here? Any advice?
UPDATE: Huge thanks to those who provided answers and explanations — I really appreciate you helping a beginner!

In your code you simply change the returned string from
$("img.photo").attr("src") without doing anything with it afterwards. This will not change the attribute in your <img> elements.
This should do the job:
$("img.photo").each(function(){this.src=this.src.replace("pictures","images")})
Here I go through all the matched elements and assign the changed src string back to each element's srcattribute.
$("img.photo").each(function(){this.src=this.src.replace("pictures","images")});
// list the changed src values in the console:
console.log($("img.photo").map((i,img)=>img.src).get())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://cdn.example.com/pictures/01.jpg" class="photo">
<img src="https://cdn.example.com/pictures/02.jpg" class="photo">
<img src="https://cdn.example.com/pictures/03.jpg" class="photo">
<img src="https://cdn.example.com/pictures/04.jpg" class="photo">

Your code snippet won't work, because that's grabbing the src attribute of the first image, and changing it, but never setting the result as the new src on the <img> elements.
Try this
$("img.photo").each((index, img) => {
img.src = img.src.replace("pictures","images");
});

Related

Problems with v-for and the :src that point to reactive variable in Vuejs

I have a problem inside a v-for, inside this v-for I create several images, which have their src pointing to an object saved in a reactive array.This array is obtained from a fetch that returns this type of objects:
{
categoria:"Web"
data:"2018-02-20 00:00:00"
idgaleria:"1"
titol:"Web technologies"
url:"http://www.laqshya.in/images/web1.png"
}
And this is the v-for inside the template:
<div v-for="entrada in entrades">
<div class="caption">
<img src="{{entrada.url}}" alt="" class="pic"/>
</div>
<h4>{{entrada.titol}}</h4>
<p>Publicat el {{entrada.data}}</p>
</div>
The result is that the template is rendered without any problem, but the images are not visible, If I look at the browser element inspector, I can see that the image element is rendered as follows
<img src="'{{entrada.url}}'" alt="" class="pic">
Does anyone know how to refer to the reactive variable within the src attribute of an image?
I have been searching the internet for the same problem, and I have seen that it happens to more people, but all refer to images that are stored locally and not on the Internet, as is my case.
Thank you!
Try
<img :src="entrada.url" alt="" class="pic"/>
or
<img v-bind:src="entrada.url" alt="" class="pic"/>
They are the same, one being the shorthand syntax. Without it, the contents in the quotes will be interpreted as a string, not code.

How should I not load the images with broken link?

I'm working on a feature, in which images are being rendered from the servers. I was working on aligning the images but found that there is a lot of white space. This was the reason, due to loading of images with a broken link.
HTML :
<div class="image-result" *ngIf="Display('images')">
<div class="col-sm-3" *ngFor="let item of items$|async">
<a href="{{item.link}}">
<figure>
<img class="res-img" src="{{item.link}}" onerror="this.style.display='none'">
</figure>
</a>
</div>
</div>
I have used onerror="this.style.display='none'" to solve the problem, but leaves a lot of white space when images are being loaded from the server. Is there any solution for it like to remove img tag whenever a image with a broken link has been detected ? I have gone through stackoverflow before asking question, but I'm not able to solve this problem. It would be great if someone can help me out. Thanks! :)
Instead of onerror="this.style.display='none'" to hide an image, you can use onerror="this.parentNode.removeChild(this)" to remove the image tag altogether.
If you want to remove the entire column, in your specific case you can do the following.
var colEl = this.parentNode.parentNode.parentNode;
colEl.parentNode.removeChild(colEl);
Or, in your HTML:
onerror="this.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode)"
You should probably move that to some JavaScript function and attach your handler by saying
element.addEventListener('error', function() { /* ... */ });
References: parentNode, removeChild, addEventListener.
If you don't care about supporting Internet Explorer, you can also use remove instead of doing the parentNode.removeChild trickery. That would be particularly useful for reducing the code length in your onerror attribute, would you choose to use it, but I don't recommend that.
A more angular-way of doing this would be:
<img src="{{item.link}}" (error)="item.brokenImage=true">
So you would have:
<div class="col-sm-3" *ngFor="let item of items$|async">
<div *ngIf="!item.brokenImage">
<a href="{{item.link}}">
<figure>
<img class="res-img" [src]="item.link" (error)="item.brokenImage=true">
</figure>
</a>
</div>
</div>
You need to listen for the error event of the image element, and assign a boolean on whether the image loaded successfully or not. Then, depending on that value angular will either show the image with the div, or remove it from the DOM.

What does this warning message mean? 'img elements must have an alt prop, either with meaningful text, or an empty string for decorative images'

Why am I getting this warning?
warning: img elements must have an alt prop, either with meaningful text, or an empty string for decorative images jsx-a11y/img-has-alt
It's showing line number 13 but there is nothing props is using.
It means when you create an image in your HTML, you should include an alt attribute for the benefit of screen readers and text browsers.
<img src="url" alt="description of image">
Images should have an alt property. The alternate property comes into picture in several cases like the card not getting downloaded, incompatible browsers, or the image getting corrupt. You need to pass in a prop called alt to the image.
Also, Alt tag is used by screen readers for visually impaired. Therefore it is considered as a good practice to always add a ALT tag to the image component.
Accessibility
It means that your <img> tag MUST have an alt attribute on it like so:
<img src="pathToYourImage.extension" alt="My Awesome Image">
In case if the image isn't loaded then the text inside the alt attribute will be shown instead.
I had the same error. Basically, you should not include these words in alt attribute. image or picture, or photo
// avoid using image or picture, or photo
// do
<img src="foo" alt="nice"/>. // good
// don't
<img src="foo" alt="foo is coming "/>. // bad
It means that your image need a description and this is a property in the img tag called alt so use this as long as you write in JSX & React :
<img src={ImageImported} alt="description of image"/>
I had a similar error with this code.
<img src={props.contacts.imgUrl}/>
Solution: Notice the alt= position on the image anchor outside the curved parenthesis
<img src={props.contacts.imgUrl} alt=""/>
This error means that you haven’t added the "alt" property. This property is mandatory, so you can not ignore it.
To get rid of this error you should set the alt attribute and pass some text there. It's like a description of your photo. This text will be used in cases when your picture is not loaded or when browser couldn't find your image by provided path (src attribute).
<img src="path_to_your_image" alt="alternative_text_of_your_image"/>
in the alt attribute do not put the image or Image because those words are reserved for react
Try this one :
<input type="image" img src = {'url'} alt="photo" />
(I have used `` not the single quotation marks for the url)
I had this an error when using ESLint in React for this:
<img src={frontDefault} />
Add this
alt=''
This is how it must be for it to work
<img src={frontDefault} alt='' />
In my case, this error was inside the REACT, and it happened because it was like this, <img src={{RedLed} } style={{width:'50px'}}/>, that way I was giving this error. The error was that I put two braces around the img call and I only needed one brace like that, <img src={RedLed} style={{width:'50px'}}/>
The element includes the alt property, which will prevent the image from having any alternate text,`

HTML Javascript Combine SRC, Link, ALT tags

I am wondering if anyone knows a way to combine the "a href", "img src", and "alt" tags. We deal with a large amount of images and it is pretty tedious copying and pasting the same thing for all three fields for each picture in dreamweaver. Doing it once would be ideal. From what I have seen there is probably not much of a chance in doing this. I am using either HTML or Javascript.
<a href="../../0_Images/CRG_UnitType.jpg" target="_blank">
<img src="../../0_Images/CRG_UnitType.jpg" alt="CRG_UnitType.jpg" width="775" height="617" border="2" class="picture">
</a>
AngularJS can also solve this problem. Source it in your HTML and set up a controller that includes your image data, and then you can use ng-repeat. The result is something like this.
<div ng-repeat="image in images">
<a href ="{{image.href}}" target="_blank">
<img SRC="{{image.src}}" width="{{image.width}}" height="{{image.height}}" border="2" class="picture">
</a>
</div>
First of all, your alt attributes should not contain your image file name, they should be used to describe the content of images in case they don't load, or in case someone visually impaired navigate through your website.
To answer the question, you definitivly need to use some server-side language to save time.
You could for instance display all your images quite easily with PHP by looping through an array of files and titles.
You need some basic understanding of this language (or any other server-side language) before doing so but the time you'll spend doing so won't be lost.
It's possible,
you can use jquery to do what you want, and if the src is the same of the href as in your example the way is:
In HTML use only image, and place an additional class:
<img src="../../0_Images/CRG_UnitType.jpg" alt="CRG_UnitType.jpg" width="775" height="617" border="2" class="picture auto_add_link">
Now add jquery function:
$( ".auto_add_link" ).wrap(function() {
return '';
});
Not so pretty, but it works
Demo on jsfiddle

Make html valid if adding new tag for <img>

I have html img list like this one:
<img src="over.png" width="150" heigh="72" />
<img src="2_over.png" width="150" heigh="72" />
<img src="3_over.png" width="150" heigh="72" />
but these images are quite large. I need to make it that it will load one by one "like ajax". But I cant load it from javascript in the begining, becouse it is our cms desing like that and we will have big troubles if i will change it. So what i am planning to do is:
<img src="" width="150" heigh="72" path="over.png" />
and load it one by one with javascript and replace src, but the html will not be valid. Can any one give me any solution how to implement it with valid html?
If putting the data somewhere is your sole problem, HTML5 supports data- attributes, which let you add arbitrary attributes to elements. It remains valid as long as the attribute name starts with data-. For instance:
<img src="" width="150" height="72" data-path="over.png" />
This feature, while not "valid" HTML4, should still work on all browsers as unknown attributes on tags are simply ignored (and kept as is).
Though, you may also search for a way to do it only with JavaScript. I don't really understand how dynamically adding images could break your CMS.
Also, the alt attribute is required for images (make it blank if you don't have anything useful to write instead), and I'm not sure a blank src attribute is valid (you may want to put a loading image's path instead).
set a valid url in the image before you call the javascript function, for instance like this:
<img src="blank.gif" alt="Blank Image" width="10" height="10" />
And as for the "path" attribute, you could put the link to the image in the alt attribute. That way your image tag will be valid.
<img src="blank.gif" alt="myImage.jpg" width="10" height="10" />
Then you can use javascript to fetch the image path from the alt attribute, and insert it in the src attribute when loaded.
Those images should be thumbnails, correct? So you're downscaling large images via HTML to small sizes. The best way would be, honestly, to provide already downscaled images as thumbnails.
One solution is to have a small image loading image and set that as the source for all the images until your javascript has loaded the relevant image.
<img src="loading.png" data-path="over.png" height="50" alt="Over" width="150">
You may want to check out JAIL, the jQuery Asynchronous Image Loader:
While it may be slightly more than what you need, its got lots of options available and its less code you have to write!

Categories

Resources