Just want to ask what is recommended to use with Angular, standard html src or Angular [src]? And why?
Edit: I have following code in my html component:
<img class="logo" src="../app/media/appLogo.png">
It is fine? If not, how should I change it to work together with [src]?
Edit2: Is there any other, better way to do it, instead of plain html src? Or this is the best solution actually?
[...]="..." is for object binding ...="{{...}}" is for binding with string interpolation. If you want to bind a string it doesn't matter what you use. If you want to bind an object or array value you need to use `[...]="...". Besides that it's entirely up to you.
<img class="logo" src="../app/media/appLogo.png">
Is not related to Angular2 at all, thats just plain HTML (no [] and no {{}}). If you add [] around src, then Angular will treat ../app/media/appLogo.png as an expression, which it clearly isn't.
When DomSanitizer is used [src]="..." is mandatory because the value no longer is a string, but an object and using {{}} would stringify it in an invalid way.
Using regular src sets the Attribute where setting [src] sets the property. Considering that for an image (I assume you're talking about an image but you don't say) the src attribute is used to set the corresponding property they will both work.
There is one big reason to use [src] though. Browsers tend to start downloading whatever you put in the src attribute while parsing the html. So lets say you do this:
<img src="{{myImgSrc}}"/>
The browsers will often immediately start downloading {{myImgSrc}}, which will lead to a 404 in the console. Using the following is therefor slightly better:
<img [src]="myImgSrc"/>
If you have static anchor link, then go ahead with
<img class="logo" src="../app/media/appLogo.png">
When binding from the component, then either of the below will work.
<img class="logo" [src]="image_src">
<img class="logo" src="{{ image_src }}">
In component.ts
image_src: string = '../app/media/appLogo.png';
Related
The title already tell's a little bit. I'm getting a list of documents with links and images like this:
<img class="Thumbnail" src="sourcetothepdfimage.png" id="/path/pdf.png"/>
The only two things that may differ are src and id. What I try to reach now is to replace the image src depending on its ID. The ID may be /path/pdf.png or /path/word.png or something completely different (which I don't know yet).
What would be the recommended way to achieve this? I have three different images for the replacement (one for PDF, one for word files and one generic for all other unknown file types).
I think document.getElementByID doesn't make that much sense because I only know two fix IDs. With this I can change the src for PDF and DOCX but not for any other, right?
So document.getElementsByClassName would be the targeted solution, but how can I iterate through all five or more listed elements with the class "Thumbnail"?
I'm barely new to the Dev world and like to learn it.
It's simple using jQuery.
// get all img's using class selector
// and use `attr()` method with callback which iterate internally
// within the callback return the id( within callback this refers to the current element DOM object)
$('.Thumbnail').attr('src',function(){
return this.id
})
<img class="Thumbnail" src="sourcetothepdfimage.png" id="/path/pdf.png"/>
Try (no jquery)
[...document.querySelectorAll('.Thumbnail')].map(img=> img.src=img.id);
console.log([...document.querySelectorAll('img')]);
<img class="Thumbnail" src="sourcetothepdfimage.png" id="/path/pdf.png"/>
<img class="Thumbnail" src="sourcetothesomimage.png" id="/path/pdf2.png"/>
<img class="Thumbnail" src="sourcetothedocimage.png" id="/path/doc.docx"/>
I have a web site with an image slider. I keep the some of the image tags empty as the images load on when slide comes into view for faster page load. The image tags defined as follows:
<img data-src="img/portfolio-desktop1-small.png" src="" alt=""/>
What I'm doing is on slide function I change the src to data-src with jQuery animation. The slider works great. My problem is when I try to validate it in w3c validation tool it gives the following error:
Line 131, Column 179: Bad value for attribute src on element img: Must be non-empty.
...data-src="img/portfolio-desktop1-small.jpg" src="" alt=""/>
Syntax of URL:
Any URL. For example: /hello, #canvas, or http://example.org/. > Characters should be represented in NFC and spaces should be escaped as %20.
Is there anyway to fix this without altering the JavaScript or CSS? If I leave it like this what can be the possible harmful outcomes of this matter?
Set the image src attribute to #:
<img data-src="img/portfolio-desktop1-small.png"
src="#" alt="Thumbnail">
The HTML passes the W3C validator just fine, and modern browsers know not to try to load the non-existent image.*
For contrast, using a src value that references a non-existent file results in an unnecessary HTTP request and an error:
<img data-src="img/portfolio-desktop1-small.png"
src="bogus.png" alt="Thumbnail">
Failed to load resource: The requested URL was not found on this server.
*Note: I've read conflicting information on how browsers handle the #. If anyone has definitive information, please add a comment.
Also see related answer by sideshowbarker about the action attribute: https://stackoverflow.com/a/32491636
Update: November 2022
It seems the src="#" trick used to be a decent workaround but it's no longer a good idea to send that to the browser.
So, I created a build tool to convert occurrences of src="#" in source HTML to inline data URLs of a tiny invisible one pixel SVG appropriate for the browser.
Build tool img-src-placeholder:
https://github.com/center-key/img-src-placeholder (MIT License)
The interesting bits are:
const onePixelSvg =
'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"></svg>';
const dataImage = 'data:image/svg+xml;base64,' +
Buffer.from(onePixelSvg).toString('base64');
html.replace(/src=["']?#["']?/gm, `src="${dataImage}"`);
The resulting HTML will have <img> tags like:
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxIiBoZWlnaHQ9IjEiPjwvc3ZnPg=="
alt=avatar>
The advantage of using a build tool is that:
Source remains uncluttered
HTML always validates
The inline data URL prevents the browser from making an unnecessary and invalid network request
What happens if you just remove the src attribute then add it on the fly when you need it. The src attribute isn't required. And in my opinion I wouldn't worry about what the w3c validation tool says anyway. As long as you test it in the necessary browsers and it works.
Update Jan 2021. The src="#" trick works now on the validator at https://www.w3.org/TR/html-media-capture/
If anyone still looking for the answer, the src="/" code resolves the w3c validator complains and doesn't produce additional request like the solution with the # character.
I am a javascript beginner. Could anybody tell me why there are data-src and src both exist? What's the objective of those two, respectively?
One more problem is what href="javascript:;" mean? why there is nothing after semi-colon??
Here is my code:
<img style="width: 400px; height: 600px;" id="PicSrc" data-src=
"http://image.xcar.com/attachments/a/day_131222/2013122214_59cc5328b60142f66b98nD1UtoNKWnqt.jpg"
src="%E8%BD%A6_files/2013122214_59cc5328b60142f66b98nD1UtoNKWnqt.jpg"></a><a id="collect" class="collect"
style="display: block;"
href="javascript:;"></a>
<a id="zoom" class="zoom" style="display: block;" href="javascript:;"></a>
data-src is a data attribute. You can read a good article about them here
Essentially data attributes are for storing private data just for the programmer that is not interpreted by the browser or seen by the user.
In this case it's probably that the data-src attribute links to the zoomed version of the image. When the zoom link is clicked some JavaScript inspects the data attribute and alters the image.
Any attribute that starts with data- is a custom attribute. Your application can use them however you see fit, but the browser doesn't do anything specific with them.
The href value is an empty javascript block which means that clicking the link won't take you to a new page, though you should give it a value of void(0) to ensure it works correctly. In these cases your application will typically have custom click handlers on the link that execute some action when the link is clicked. That click handler may use the value of data-src.
I'm working on a Sharepoint website. I don't have access to the webparts code. I can only change master pages with JavaScript.
One of the webpart has a bug. It changes the <img> with a bad SRC value.
example:
should have
<img alt="img" src="http://www.apicture.png" style="margin:5px" /><br /><br />
but have
<img alt="img" src="http://www.apicture.png" style="margin:5px" /><br /><br />
I tried to match and replace but the innerHtml broke the others scripts.
How can a repair my with JavaScript ?
Edit:
I have the code:
var markup = document.documentElement.innerHTML;
markup = markup.replace(/src=\".*?(http:\/\/[^\"]+)\"/g,'src=\"$1\"');
document.documentElement.innerHTML = markup;
but it broke my webpage.
Since the DOM has already been broken, you need to take a step back and try to salvage the HTML.
1) Find the parents of the broken elements. While search&replace inside the document.body.innerHTML would probably work, you shouldn't really let regexes anywhere near large chunks of HTML. Performance is a concern as well, albeit a lesser one.
<img alt="img" src="<a href="http://... will get parsed by the browser as an image with the source "<a href=".
With jQuery, you can simply ask $('img[src="<a href"]') to get the images. Except in IE<8, you can use querySelectorAll with the same selector. If you don't have jQuery, and want to support IE7, you need to use getElementsByTagName with manual filtering.
If you are really lucky, you can find the parent via getElementByID (or the equivalent jQuery).
This is the easy part.
2) Your HTML doesn't validate, and the browser had already made some effort to fix it. You need to reverse the process. Predicting the browser actions is problematic, but let's attempt to.
Let's see what the browser does with
<img src="http://www.test.com/img/image-20x20.png" style="margin:5px" />
This is how Chrome and Firefox fix it:
<img src="<a href=" http:="" www.test.com="" img="" image-20x20.png"="">http://www.test.com/img/image-20x20.png" style="margin:5px" />
IE9 sorts the attributes within img alphabetically in innerHTML (o_0) and doesn't HTML-escape the < within src. IE7-8 additionally strip ="" from the attributes.
The image attributes will be hard to salvage, but the text content is unharmed. Anyways the pattern can be seen:
everything starting at <img and until src= should be preserved. Unfortunately, in IE, the arguments are rearranged, so you have to preserve the incorrect tags as well. src="..." itself must be removed. Everything past that is [incorrect] in modern browsers, but in IE, proper attributes could have crept there (and vice versa). Then the image tag ends.
Everything that follows is the real URL, up until the double quote. From the double quote up until the HTML-escaped /> are attributes that belong to the image tag. Let's hope they don't contain HTML. CSS is fine (for our purposes).
3) Let's build the regex: an opening IMG tag, any attributes (let's hope they don't contain HTML) (captured), the src attribute and its specific value (escaped or unescaped), any other attributes (captured), the end of tag, the URL (captured), some more attributes (captured) and the HTML-escaped closing tag.
/<img([^>]*?)src="(?:<|\<\;)a href="([^>]*?)>([^"]+?)"(.*?)\/>/gi
You might be interested in how it's seen by RegexPal.com.
What it should be replaced by: The image with the proper attributes concatenated, and with the src salvaged. It might be worthy to filter the attributes, so let's opt for a callback-replace. Normal attributes contain only word-characters in their keys. More importantly, normal attributes are usually non-empty strings (IMG tags don't have boolean attributes, unless you are using server-side maps). This will match all empty attributes but not valid attribute keys: /\S+(?:="")?(?!=)/
Here is the code:
//forEach, indexOf, map need shimming in IE<9
//querySelectorAll cannot be reliably shimmed, so I'm not using that.
//author: Jan Dvorak
// https://stackoverflow.com/a/14157761/499214
var images = document.getElementsByTagName("img");
var parents = [];
[].forEach.call(images, function(i){
if(
/(?:<|\<\;)a href=/.test(i.getAttribute("src"))
&& !~parents.indexOf(i.parentNode)
){
parents.push(i.parentNode)
}
})
var re = /<img([^>]*?)src="(?:<|\<\;)a href="([^>]*?)>([^"]+?)"(.*?)\/>/gi;
parents.forEach(function(p){
p.innerHTML = p.innerHTML.replace(
re,
function(match, attr1, attr2, url, attr3){
var attrs = [attr1, attr2, attr3].map(function(a){
return a.replace(/\S+(?:="")?(?!=)/g,"");
}).join(" ");
return '<img '+attrs+' src="'+url+'" />';
}
);
});
fiddle: http://jsfiddle.net/G2yj3/1/
You can repair src attribute with regex but it won't repair the entire page. The reason is that web browser is trying to parse such bad HTML and produces weird output (extra elements etc.) before JS is executed. Since you cannot interfere the HTML parsing/rendering engine, there's no reasonable way other than changing the original content to fix this.
I want to use the same string in my img "src" in my "onclick" as a parameter to a function. What's the easiest way to do this? It works fine if I type it out both times but it doesn't look nice.
Here is an example so you can see what I mean...
<img src="/images/image1.jpg" onclick="doStuff('/images/image1.jpg')"/>
I'm wondering if there is a simple way to have the src in the onclick too that doesn't require me to write it out again? So I can use a general onclick for each image that needs to be clicked.
<img src="/images/image1.jpg" onclick="doStuff(this.src)"/>
doStuff(this.src);
The easiest thing is to pass the object itself into the function. So:
<img src="/images/image1.jpg" onclick="doStuff(this.src)">
Will do what you want, I believe.