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' />
Related
im trying to store an image in HTML that comes from a url source in a variable using JavaScript. Could someone show me what code is required? i have started it off...
var productImage = document.getElementById("productImg").//??;
<img id="productImg"
src="https://i5.walmartimages.com/asr/1735db1c-d84f-417a-b871-27b63ee2b2e6_1.9a18f15c0e0fa321d0c5d073875b9738.jpeg?odnWidth=undefined&odnHeight=undefined&odnBg=ffffff" >
You were close. To obtain the value of an HTML element's attribute, you can access that attribute as a property of the DOM element.
var productImage = document.getElementById("productImg").src;
console.log(productImage);
<img id="productImg"
src="https://i5.walmartimages.com/asr/1735db1c-d84f-417a-b871-27b63ee2b2e6_1.9a18f15c0e0fa321d0c5d073875b9738.jpeg?odnWidth=undefined&odnHeight=undefined&odnBg=ffffff" >
You can use the src property.
var productImage = document.getElementById("productImg").src
You can also use the src property to set a new URL for the image if you want to replace it.
var productImage = document.getElementById("productImg");
productImage.src = URL
How can I keep onclick="" value with JQuery replaceWith ? I'm making a assets system that preload every image and put it on a Javascript image() object, and using a special data attribute for img urls
<img data-assets="images/test.png" onclick="alert('test')">
turn into : (using jquery replaceWith)
<img src="assets/images/test.png">
What I want:
<img src="assets/images/test.png" onclick="alert('test')">
My code:
$("[data-assets]").each(function() {
$(this).replaceWith(Game.Preloading.Assets.Images[$(this).data('assets')]);
});
How can I fix that ? Thanks
While iterating over each [data-assets] element, you could set the corresponding onclick attribute before replacing the element:
$("[data-assets]").each(function() {
var $newImg = $(Game.Preloading.Assets.Images[$(this).data('assets')]);
$newImg.attr('onclick', $(this).attr('onclick'));
$(this).replaceWith($newImg);
});
However, it would be better to just add a src attribute on the existing element rather than replacing it:
$("[data-assets]").each(function() {
this.src = $(Game.Preloading.Assets.Images[$(this).data('assets')]).attr('src');
});
Ideally, you should be using unobtrusive JavaScript and avoiding the inline JavaScript event listeners, but both of the above snippets should work.
I think you would be better off to simple query for your attribute, then use the each method to update the SRC attribute on each matched element.
Im on my phone so a more detailed answer is difficult...
But here goes
$("[data-assets]").each(function(){ $(this).attr("src", Game.Preloading.Assets.Images[$(this).data('assets')]); });
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.
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')
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;