How to set a fallback image for img setAttribute - javascript

I have an img element:
var photo = document.createElement("img");
which is feed by photos with name stored in an array of objects, so I "feed" the photos like this:
photo.setAttribute('src', './pics/' + myarray[id].Name + '.jpg');
And it works perfect.
The only thing not working is to set an attribute with a default photo for the element that don't have a pic.
I have tried to do a setAttribute line above that one, setting a "default" picture for all the elements, hoping that the second line would replace with proper picture the elements that have one, and leave the default ones untouched, but no... console.log still showed a message of expecting a name+jpg scheme, it totally ignored my previous line (so I am pretty sure is not how it works).
So if you have an img element with many instances through an array, what is the best way to assign a default picture to the elements whose picture is not specified in purpose?
Thanks!

Can you use jQuery. This is a solution for the problem you described. If an image comes back as a 404 then it gets the default image applied
http://jsfiddle.net/gunderson/D3DSt/
var photo = document.createElement("img");
photo.setAttribute("id", "myPhoto");
$('body').append(photo);
$("#myPhoto").attr("src", 'alogo3w.png').error(function() {
$(this).attr("src", "https://www.google.com/images/srpr/logo3w.png");
})
​

Just set only the default if neccessary
photo.setAttribute('src', './pics/' + ( myarray[id].Name ? myarray[id].Name : 'default' ) + '.jpg');

Related

Javascript that automatically fills in HTML file path for images

I'm trying to use window.location.pathname and injecting innerHTML to generate the file paths for an image so all I need to do is type fileName.png in a div in the html body and have the javascript generate the file path behind it so that it displays the image in the rendered website. This is for images that aren't stored in the same folder as the working file.
I've had mild success but it only works for one image per page which isn't very helpful.
I've gotten this code to work for one image per page:
<div class="picName">pic.png</div><div id=<"shortcut"></div>`
<script>
var relativePath = window.location.pathname;
var picName = document.getElementById('matts-shortcut').previousElementSibling.innerHTML;
document.getElementById("matts-shortcut").innerHTML =
'<src=\'/images' + relativePath + '/' + picName + '\'>';
</script>
The solution below pulls images names from with Divs using .querySelectorAll() which returns a DOM NodeList. The NodeList is useful because it has a forEach() method that can be used to loop over each item is the list. Loop over each list item using it's textContent property as the image name. Then you'll need to create a new image element for each image. To do that you can do something similar to this.
let relativePath = "https://dummyimage.com"; // replace the url with path name (maybe window.location.path)
// create a reference to the input list
// querySelectorAll return a NodeList
let inputNameList = document.querySelectorAll('.image-name');
// Loop through each image name and append it to the DOM
// the inputNameList (NodeList) has a "forEach" method for doing this
inputNameList.forEach((image) => {
let picName = image.textContent;
// Create a new image element
let imgEl = document.createElement('img');
// Set the src attribute of the image element to the constructed URL
// the name of the picture will be the div text content
// This is done with a template literal that you can learn about here:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
imgEl.src = `${relativePath}/${image.textContent}`;
// Now we have a real image element, but we need to place it into the DOM so it shows up
// Clear the image name
image.textContent = "";
// Place the image in the Div
image.appendChild(imgEl);
});
<div class="image-name">300.png</div>
<div class="image-name">200.png</div>
<div class="image-name">100.png</div>
<div class="image-name">400.png</div>
EDIT: In response to Ismael's criticism, I've edited the code slightly and commented every line so you can learn from this answer. There are two hyperlinks referenced in the code to help you think about coding in a modern way and so you can interpret modern code you read more easily.
About:
Arrow functions
Template Literals
Edit 2:
With further clarification, the answer has been amended to pull the image file names from Div elements already in the DOM.
Let ID equal your element's id
Call on:
document.getElementById(ID).src = "image_src"
When you want to change images, like an onclick action or as part of a function.

Change the background image of an element

So I'm having some issues with creating a really simple function that's supposed to change the background image of a div element to match whatever image is being hovered upon by the mouse.
The HTML looks like
<div id = "image">
Hover over an image below to display here.
</div>
<img class = "preview" alt = "Styling with a Bandana" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover = "upDate(this)" onmouseout = "unDo()">
That's just the div element I want to change, alongside one of the images.
So our function is supposed to take in an image element as a parameter. But I'm having a lot of trouble accessing this image parameter's src attribute and using that in the .style.backgroundImage property.
My current code is:
function upDate(previewPic){
var div_element = document.getElementById('image').innerHTML;
var picurl = "url(previewPic.getAttribute('src'))"
div_element.style.backgroundImage = "url(picurl)";
}
And this gets me an error of Uncaught TypeError: Cannot set property 'backgroundImage' of undefined on my browser console.
If you can tell, I'm trying to put the actual div object into a variable, then put the picture url into a variable. Then I want to use the .style.backgroundImage property. This isn't working. But the solution is probably really simple. What could I do to fix it?
There are multiple issues with your code.
Getting the inner html is just setting your variable to a string representation of what's inside the element, which is nothing since it's an <img> tag.
Essentially, you're putting everything in quotes, so javascript doesn't do anything with it.
Remove the .innerHTML from the first line of the function, and then take the parts javascript needs to evaluate as code out of the quotes.
Change your code to:
function upDate(previewPic){
var div_element = document.getElementById('image');
var picurl = "url(" + previewPic.getAttribute('src') +")"
div_element.style.backgroundImage = picurl;
}
This should work.
If I understand on some image hover you want to change div background?
I would do it with jquery:
$('img').hover(function(){
$('div').css(''background-image:'url("image_link")');
});

Use javascript to click all images based on src value only

I want to click all the links on a page that have a certain image src.
I know I can do the following if I know the id:
alert(document.getElementById('image').src);
But I know know the src and nothing else is there. No id, alt or title, nothing only src.
Anyone have any idea on how to do this? Thanks!
Easy.. though please read jquery's documentation when you get the chance:
$("img[src='src_goes_here']").trigger("click");
Assuming you want to click the link that has a child image with a particular source..
$("a img[src='src_goes_here']").parent().trigger("click");
I'm not sure what you mean with "clicking links with a certain image-src", as clicking would be a user-interaction and links don't tend to have a src - attribute like the <img>-tag
Anyhow, using jQuery as example, there is something called "Attribute-Selectors", in your case the Attribute Equals Selector (jQuery-API) should do the trick:
var yourSource = "/path/to/image.jpg";
var myImages = $('img[src="'+ yourSource +'"]');
So, for example, if your images are inside a link, all you'd need to do is:
myImages.parent().trigger('click');
but I really don't know what good that should do
$('img[src="' + yourKnownSrc + '"]').click();
In case you want to click links "having" an image:
$('a').has('img[src="' + yourKnownSrc + '"]').click();

Java Script Mousovers

I am implementing a mouseover, which changes the background of a div onMouseDown, and onMouseUp, I am also trying to preload the images.
This is what I have so far;
if(document.images) {
buttonDown = new Image();
buttonDown.src = "buttonDown.png";
}
function down(affect) {
affect.style.backgroundColor="#333333";
affect.style.color="#ffffff";
affect.style.background = buttonDown;
return true;
}
the div uses onMouseDown="down(this);"
This doesn't work. The only part that doesn't work is -- affect.style.background = buttonDown;
I left out the script tags, but they are all there and work as they should.
My question is how do I assign the background property to a preloaded image verses just using a string to assign the image by name.
First, I think you are accessing the wrong style attribute; If you are going to use backgroundColor, may as well go with the more specific backgroundImage.
Second, it requires a string, not an Image Object.
Try this:
affect.style.backgroundImage='url(' + buttonDown.src + ')';
All that said, I would look into image Sprites and HTML classes (CSS) =)
I did some more research and this is what I found. You can preload the images by using a div which is set to style="display:none" and within that div include the images.
As long as the next time you refer to the image, you use the same path it will be preloaded.

How to update HTML element with jQuery and Galleria?

I am using Galleria for a slideshow. I want to place a small, 'Larger' link beside the stage.
I have this code for the 'Larger' button:
this.fullres = this.create('div', 'fullres');
this.get('fullres').innerHTML = 'Larger';
this.appendChild('fullres', this.fullres);
I have this code that assigns every <img>'s rel= tag to the full sized image URL from the page's custom field:
<img ... rel="<?=$attachments[$i]['fullres']?>" />
With JQuery, I am hoping to pull the active image's rel= tag value and append the .fullres href tag. This is the code I have so far, but it doesn't work:
var title = $(.images).attr('rel'); // pulls the fullres url from the rel tag
$('.galleria-fullres').attr('href', ); //append the galleria fullres href with the rel info
Galleria doesn't really work like that. But what you can do, is to create a button to enter fullscreen and have a larger image in fullscreen.
Something like this:
$('#galleria').galleria({
// other galleria options here
dataConfig: function( img ) {
// get the fullscreen image
return {
big: $( img ).attr('rel')
};
}
});
var galleria = Galleria.get(0);
$('#fullscreen-button').click(function() {
galleria.enterFullscreen();
});
I have to say I can't see how this would work as it is...
Do you know you have a typo at: $(.images)? Should be $('.images').
And have you left out the second parameter at $('.galleria-fullres').attr('href', ); on purpose? Shouldn't this be $('.galleria-fullres').attr('href', title); ?
How can the jquery work by referencing the elements by classes? You are getting an array of elements, not just one. I guess this is only an excerpt of your code? Am I missing something?
Could you perhaps post the html of a sample of these elements as seen in the browser? It should be a pretty easy thing, but I really can't see the whole picture with those lines only.

Categories

Resources