Get image src without loading the image? - javascript

I have a html snippet being returned through ajax. The snippet is an <img> tag.
<img src="image.jpg" />
I need to extract the value of the src attribute without loading the image initially. The reason for this is the src attribute contains a partial path that I need to manipulate in my app to load the image properly.
I have the following code currently extracting the src attribute:
var src = $(value).attr('src');
However, this causes the image to load, resulting in a 404. I would like to avoid this unnecessary request.
How can I extract the value of the src attribute without causing the browser to load the image?

I solved this by changing the name of the src attribute before loading it into jquery.
value = value.replace('src', 'data-src');
var src = $(value).attr('data-src');
Doing this allows me to extract the value without causing the browser to attempt to load the images.

Your best bet is probably to output a data tag on the image. You can then manipulate this using jQuery and then use it to write the final image path.
So you'd do something like this in your HTML:
<img data-img-src="abc.jpg" class="my-image" />
Then in your jQuery:
var path = $('.my-image').data('img-src');
console.log(path); // Do something here, then write the new path with:
$('.my-image).attr('src', new_path);
EDIT: Sorry I just re-read the bit where it's coming via AJAX. In that case, you can probably use the data callback of your ajax request to strip the src from the image.

$.ajax('someURL.html', function(data){
var html = data.replace(/\ssrc/g, ' data-src'),
img = $(html),
src = 'some/path/' + img.data('src');
img.attr('src', src);
$('#container').append(img);
});

If you just have the string , like <img src="image.jpg" /> why dont you go for regex?
Something like: /[\"\'][a-z0-9A-Z\.]*/.
PS:My regex skills are poor,so you could manipulate it accordingly.

Use
var string = '<img src="image.png">';
var matches = string.match(/src\=("|')(.*?)\1/);
console.log(matches[2]);

You can simply remove the attribute after accessing it.
This will not load the invalid image, as you can confirm in your console:
var s= $('<img src="invalidURL.jpg">'),
src= s.attr('src');
s.removeAttr('src');
console.log(src);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Remove removeAttr(), and it will attempt to load the image.

Related

Setting the img src to be the img src on another website based on img id

Is it possible to get the img src from a completely different web page if you have the img ID and then use that as the img src on your own website?
That way, when the image changes on that other website, it will also change on yours.
So, for example, on www.abcdefg.com/1234567/ there is an image.
The img id for the image in question is "image-tag"
I would like to be able to get the src of that image by using the img id (image-tag) and use it as the img src on my own web page.
$link = 'http://www.bamuel.com/';
$content = file_get_contents($link);
$first_step = explode( '<img id="epic article">' , $content );
$second_step = explode("</img>" , $first_step[1] );
echo $second_step[0];
You can possibly able todo it in PHP
It does not go that way.
Let's say your desired id is
id = "image-tag"
and src = "http://www.abcdefg.com/1234567.png"
you wish the line would look like this:
<img id="image-tag">
For it to get the source(src),
You could do this with JavaScript:
var image_tag = document.getElementsByTagName('img')
var attr_val = image_tag.getAttribute('id')
if (attr_val == 'image-tag'){
attr_val.src = "http://www.abcdefg.com/1234567.png";
}
This way, from your example, whenever you declare any img with id = "image-tag", the source will automatically be referenced to the site as required.
No, it is not possible.
CORS prevent you from sending an ajax request to fetch HTML from a different origin, but it is possible to fetch the other website from a server and extracts the image tag to get the image src.

Add image src to array in JavaScript without http-address

Problem:
Trying to add image src to array without the website URL (http://).
HTML code:
<img src="images/pink.jpg" alt="Photo" class="pink">
JS code:
var photoArray = [];
photoArray.push(this.parentNode.getElementsByTagName("img")[0].src);
alert(JSON.stringify(photoArray));
Desired result:
http:// and so on adds to the array but all I want the array to save is "images/pink.jpg" without any http:// beginning.
Use .getAttribute('src') instead. It will fetch exactly what you need.
Working Code Snippet:
var photoArray = [];
photoArray.push(document.getElementsByTagName("img")[0].getAttribute('src'));
alert(JSON.stringify(photoArray));
<img src="images/pink.jpg" alt="Photo" class="pink">
Readup: .getAttribute() | MDN
This is because the browser expands the src property to the full URL. Use getAttribute to the the attribute value instead of the expanded src property.
this.parentNode.getElementsByTagName("img")[0].getAttribute('src')

Javascript setAttribute returning nothing

So i'm trying to set an image as a background, and the image source is pulled from a variable. I've tried different methods from the setAttribute to src= ect. Can you guys tell me what i'm missing?
Here is my html code i'm trying to set the image too i've tried with the img tag not having the src in the tag to start as well still nothing:
<body onload = "mapThing()">
<img id = "elephant" src=''>
<canvas id="processing"></canvas>
</body>
here is the function that has the setAtt elements in it:
function mapThing(){
mapUrl = getValue("urlValue");
var backImg = parseUrl(mapUrl);
console.log(backImg);
function setBack(){
document.getElementById('elephant').setAttribute('backImg', 'src');
}
setBack();
}
the backImage is a url in the form of:
http://maps.googleapis.com/maps/api/streetview?size=600x600&location=40.736315,-73.992243&fov=75&heading=23.58&pitch=10
You have backImages between quotes in setAttribute.
And also have the parameters inverted.Try removing them and change parameter order:
document.getElementById('elephant').setAttribute('src',backImg);
Have you tried the following? You are using the setAttribute method wrong.
document.getElementById('elephant').style.backgroundImage = backImg;
Try simple src is valid attribute of <img/> element, you can access as Object, see below
document.getElementById('elephant').src = backImg;

Change attribute from data-src to src WITHOUT jQuery

I am building a lightbox, in pure JavaScript. I currently have my images loading via AJAX, but i know it is easier to just have the img data-src attribute being replaced onclick to src.
I however have NO idea how this is done in pure JavaScript, by that i mean, without using any libraries.
Can anyone tell me how this is done?
to sum up: How do i change ex:
<img data-src="URL"/>
to:
<img src="URL"/>
without jQuery.
You can do it like shown below:
var imgEl = document.getElementsByTagName('img');
for (var i=0; i<imgEl.length; i++) {
if(imgEl[i].getAttribute('data-src')) {
imgEl[i].setAttribute('src',imgEl[i].getAttribute('data-src'));
imgEl[i].removeAttribute('data-src'); //use only if you need to remove data-src attribute after setting src
}
}
The above code will fetch all img tags, check if they have a data-src attribute and if present, replace it with src.
Demo Fiddle
Get a handle on the image element, and then set it's src property, using the value from getAttribute().
Plain Javascript doesn't have any helper functions to handle data-* attributes, it just treats them as any other attribute.
var img = document.getElementById("myimg");
img.src = img.getAttribute("data-src");
You can use forEach with querySelectorAll
var imageElements = document.querySelectorAll('img');
imageElements.forEach(c=> c.setAttribute('src',c.getAttribute('data-src')));
img{width:100px;}
<img data-src='https://cdn4.iconfinder.com/data/icons/nature-20/512/79-512.png' />

getting a webpage's image(s) with javascript

Is there a way to get an image from an outer webpage with javascript code?
I'll explain:
I have a website, lets say www.one.com, and I want to show in this website's homepage an image that exists in another website, lets say www.two.co.il
Can I do it?
Try this:
var img = document.createElement("img");
img.src = "http://www.two.co.il/image.jpg";
document.body.appendChild(img);
A convenient thing is to create first a placeholder in your HTML:
<div id='externalImage'></div>
because it will not disrupt the function if the layout changes and allows precise placement.
As for the real question on how you put an image, assuming from the tags that you use Jquery:
$("#externalImage").html("<img src=\"http://put.url.here/image.jpg\" />");
if you want to insert it into the aforementioned placeholder. Otherwise to plainly add the image to the document you can append it to the documentd BODY or elsewhere using document.body.appendChild like in the other answers.
Yes.
var image = document.createElement('img');
image.setAttribute('src', 'http://www.two.co.il/foo.jpeg');
image.setAttribute('alt', 'something suitable');
document.body.appendChild(image);
So long as you aren't trying to get content from the other site into JS (you aren't, you are create an img element in the DOM, JS has no further involvement), you won't run into the Same Origin Policy.
or simply:
$("<img src='" + imgUrl + "' alt='" + altText + "'>").appendTo("body");
make a div and give id = "div1" with height and width
<div id='div1' height='100' width='100'></div>
$('#div1').css('background-image, 'http://www.two.co.il/urImage.jpg');
it is shortest way to apply image

Categories