How to have two fallback image placeholders - javascript

This works really well for filling a placeholder in place of an image that doesn't exist.
<img src="cantfind.jpg" onError="this.onerror=null;this.src='http://placehold.it/600x600?text=No Picture'">
What I was curious about is if there was a way to do two placeholders within the onError event. So I tried doing this but the Javascript isn't coming to me. any ideas? I tried assigning the urls to variable, but I'm not sure how to check for if the first placeholder fails without doing some messy xhr request or something.

Check if the current src equals one of the placeholders and assign a new url accordingly:
onerror="
var p1='http://.......', p2='http://......';
if (this.src == p1) this.src = p2; else if (this.src != p2) this.src = p1;
"

Here's one way of doing it via recursive event handling... try loading and if it errors, then try loading the first element from the array, and set it to error with the next index on failure, until you hit an index that is out of range, at which point stop.
This caters for any number of defined placeholders in the sources array.
<img id="img" src="example.jpg" onerror="loadNextImage(0);" alt="logo image">
<script>
var imagesDir = 'path/to/images/directory/';
var sources = [ '01.jpg', 'test.gif', 'bamf.jpg', 'foobar.jpg' ];
var index = 0;
function loadNextImage(index) {
var image = document.getElementById('img');
if (index < sources.length) {
console.log('Index:', index, sources[index]);
image.onerror = function() { loadNextImage(index + 1); };
image.src = imagesDir + sources[index];
} else {
image.alt = 'No suitable image found to display';
}
}
</script>

Related

Attempting to change an image onclick via PHP/Javascript/HTML

I've looked at numerous other answers regarding this but haven't found a solution that has worked. I'm using a PHP page that contains some HTML code, with Javascript working some functions. Ideally I would select an image on the page, the image will become colored green as it is selected. I would then like to deselect the image and have it return to the original state. I can only get half-way there however. What am I missing? Is it something with post back?
Here's some code examples:
The HTML:<div onclick="changeImage(1)" id="toolDiv1"><img id="imgCh1" src="/images/Tooling/1.png"></div>
The Javascript function:
function changeImage(var i){
var img = document.getElementById("imgCh" + i + ".png");
if (img.src === "images/Tooling/" + i + ".png"){
img.src = "images/Tooling/" + i + "c.png";
}
else
{
img.src = "images/Tooling/" + i + ".png";
}
}`
The "1c.png" image is the one that is selected and should replace "1.png". There are multiple divs on this page that hold multiple images, which are named 2/2c, 3/3c, which is why the var i is included. Any insight? Thanks in advance.
You could do it something like this, it would also allow for different file names.
<img class="selectable" src="/images/Tooling/1.png"
data-original-source="/images/Tooling/1.png"
data-selected-source="/images/Tooling/1c.png">
<img class="selectable" src="/images/Tooling/2.png"
data-original-source="/images/Tooling/2.png"
data-selected-source="/images/Tooling/2c.png">
 
var images = document.getElementsByClassName('selectable');
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
function selectElementHandler(event) {
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
image.setAttribute('src', newSrc);
}
 
With comments:
// find all images with class "selectable"
var images = document.getElementsByClassName('selectable');
// add an event listener to each image that on click runs the "selectElementHandler" function
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
// the handler receives the event from the listener
function selectElementHandler(event) {
// the event contains lots of data, but we're only interested in which element was clicked (event.target)
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
// if the current src is the original one, set to selected
// if not we assume the current src is the selected one
// and we reset it to the original src
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
// actually set the new src for the image
image.setAttribute('src', newSrc);
}
Your problem is that javascript is returning the full path of the src (you can try alert(img.src); to verify this).
You could look up how to parse a file path to get the file name in javascript, if you want the most robust solution.
However, if you're sure that all your images will end in 'c.png', you could check for those last 5 characters, using a substring of the last 5 characters:
function changeImage(var i){
var img = document.getElementById("imgCh" + i);
if (img.src.substring(img.src.length - 5) === "c.png"){
img.src = "images/Tooling/" + i + ".png";
}
else
{
img.src = "images/Tooling/" + i + "c.png";
}
}

Javascript slideshow with caption issues

So I am having issues with captioning my slide show using a javascript, can somebody let me know as to where I am going wrong. My code stands as this:
JavaScript Document
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
if (index >= 5){index = 0}
var img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();
}
function CaptionSlide()
{
if( img.attr("src") == "movieImages/img1.jpg")
document.getElementById("captionbar").innerHTML="Up!";
else if(img.attr("src") == "movieImages/img2.jpg")
document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.attr("src") == "movieImages/img3.jpg")
document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.attr("src") == "movieImages/img4.jpg")
document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.attr("src") == "movieImages/img5.jpg")
document.getElementById("captionbar").innerHTML="Ice Age";
}
HTML document
<div class="slides">
<img id="img1" src="">
</div>
<input type="image" src="images/Next.png" id="button" onClick="javascript:moveToNextSlide()" title="Next" >
<div id ="captionbar"></div>
Also to note, that I get this error within the "inspect element":
Uncaught TypeError: Cannot call method 'attr' of null
REVISED
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
if (index >= 5){index = 0}
img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();
}
function CaptionSlide()
{
window.onload = function(){
if( img.src === "movieImages/img1.jpg")
document.getElementById("captionbar").innerHTML="Up!";
else if(img.src === "movieImages/img2.jpg")
document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.src === "movieImages/img3.jpg")
document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.src === "movieImages/img4.jpg")
document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.src === "movieImages/img5.jpg")
document.getElementById("captionbar").innerHTML="Ice Age";
}
}
The HTML Remains the same as before.
No error references however function does not write the text whatsoever.
Replace all img.attr('src') by img.src=="your image name".
For example:
img.src=="movieImages/img1.jpg"
As you are using pure JavaScript,you cannot use attr() which is method of JQuery.
attr() is a method brought by JQuery. If you are not using JQuery, you should keep using img.src. Another thing I noticed that might cause trouble : when you read .src from your image, you get the full path as a return (including your domain).
Your conditions would then become :
img.src === "http://yourdomain.com/movieImages/img1.jpg"
( And I just checked to be sure : http://www.w3schools.com/jsref/prop_img_src.asp mentions that the return value of img.src includes protocol and domain )
Also I think you should either define your function CaptionSlide inside moveToNextSlide so that it gains access to the updated img variable or not declare your img variable inside the moveToNextSlide function (so that the global variable gets updated instead)
Another point : you should make sure the DOM is loaded before querying elements from it (such as img) . To do so, wrap your code in a function, and assign it to the window.onload event :
window.onload = function() {
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
...
}
function CaptionSlide()
{
if( ... )
...
}
document.getElementById("button").addEventListener('click', moveToNextSlide);
}
and HTML for button :
<input type="image" src="images/Next.png" id="button" title="Next" />

Use javascript selectors without jQuery to select images

I have some images like this:
<img src="http://127.0.0.1/test/images/cat01.png" alt="00" class="cat_img">
<img src="http://127.0.0.1/test/images/cat02.png" alt="00" class="cat_img">
<img src="http://127.0.0.1/test/images/cat03.png" alt="00" class="cat_img">
and I want to select the image names (cat01.png, cat03.png and cat03.png) with javascript (without jQuery).
How can I do that ?
I have tried :
var images = Array.prototype.slice.call(document.getElementsByClassName('cat_img'));
console.log('Images '+images);
Thanks for help.
Or like this (no need to use Array.prototype.slice)
var images = Array.prototype.map.call(
document.querySelectorAll(".cat_img"),
function(img) {
var src = img.src,
lastIndex = src.lastIndexOf('/');
return src.slice(lastIndex + 1);
});
You can loop over your images array using map and return the part of the src attribute that you want (everything after the last /):
var images = Array.prototype.slice.call(document.getElementsByClassName('cat_img'));
var imageNames = images.map(function( image ) {
return image.src.substring( image.src.lastIndexOf("/") + 1 );
} );
console.log(imageNames);
jsfiddle
Here is a simple example using regex with a loop.
var images = Array.prototype.slice.call(document.getElementsByClassName('cat_img'));
for(i = 0; i < images.length; i++) {
console.log(images[i].src.replace(/.+\//, ''));
}
jsfiddle
So to build your array of names, just replace the console.log(...) line with images[i] = images[i].src.replace(/.+\//, '')

modify the end of an image source from 's.jpg' to 'o.jpg' with javascript

My CMS has a plugin for pulling in facebook images with stories. I cannot change it.
In the source it creates the image URL ends in s.jpg but I would like to modify it so it ends in o.jpg in order to pull in the largest photo type
This is the code:
<div class="post_picture">
<img src="http://photos-g.ak.fbcdn.net/hphotos-ak-ash3/534627_477964682254266_1412043521_s.jpg" alt="">
</div>
Is this possible? I would image you copy the source URL, modify the end from s.jpg to o.jpg and the replace the old URL w/ the new one.
EDIT:
Thanks everyone for your replies & solutions, below is another solution I found...
$('.div1>img').attr('src',function(i,e){
return e.replace("s.jpg","o.jpg");
})
ex - http://jsfiddle.net/designaroni/4Da2a/
function imgSrcOverwrite() {
var imgs = document.getElementsByTagName('img'),
loopImg, fbImgs = [];
// Loop through each IMG, check if it's a facebook image &
// then replace _s.jpg with _o.jpg in the src attribute
for ( var x=0; x<imgs.length; x++ ) {
loopImg = imgs[x];
if ( loopImg.src.indexOf('photos-g.ak.fbcdn.net') > -1 ) {
loopImg.src = loopImg.src.replace('_s.jpg', '_o.jpg');
fbImgs.push(loopImg);
}
}
imgs = loopImg = null;
// return array of fb images so you can do more stuff with them
return fbImgs;
}
imgSrcOverwrite();
If you're using jQuery I'd replace the second line with
var imgs = $('.post_picture img'),
http://jsfiddle.net/CoryDanielson/jmzk2/
Here's a quick example of how it may be possible.
// get image dom element
var img = document.getElementById('imageId');
// update src
img.src = img.src.replace(/s.jpg/, 'o.jpg');
If you are using jquery,
Try to access the img tag by this -
var src = '';
$('.post_picture').find('img').each(function(){
src = $(this).attr('src').toString().replace('_s.jpg', '_o.jpg');
$(this).attr('src',src);
});

Getting images to change in a for loop in javascript

So far I created an array with 11 images, initialized the counter, created a function, created a for loop but here is where I get lost. I looked at examples and tutorial on the internet and I can see the code is seeming simple but I'm not getting something basic here. I don't actually understand how to call the index for the images. Any suggestions. Here is the code.
<script type="text/javascript">
var hammer=new Array("jackhammer0.gif",
"jackhammer1.gif",
"jackhammer2.gif",
"jackhammer3.gif",
"jackhammer4.gif",
"jackhammer5.gif",
"jackhammer6.gif",
"jackhammer7.gif",
"jackhammer8.gif",
"jackhammer9.gif",
"jackhammer10.gif")
var curHammer=0;
var numImg = 11;
function getHammer() {
for (i = 0; i < hammer.length; i++)
{
if (curHammer < hammer.length - 1) {
curHammer = curHammer +1;
hammer[i] = new Image();
hammer[i].src="poses/jackhammer" +(i+1) + ".gif";
var nextHammer = curHammer + 1;
nextHammer=0;
{
}
}
}
}
setTimeout("getHammer()", 5000);
</script>
</head>
<body onload = "getHammer()";>
<img id="jack" name="jack" src = "poses/jackhammer0.gif" width= "100" height ="113" alt = "Man and Jackhammer" /><br/>
<button id="jack" name="jack" onclick="getHammer()">Press button</button>
Following on what Paul, said, here's an example of what should work:
var hammer=["jackhammer0.gif","jackhammer1.gif","jackhammer2.gif","jackhammer3.gif",
"jackhammer4.gif","jackhammer5.gif","jackhammer6.gif","jackhammer7.gif",
"jackhammer8.gif","jackhammer9.gif","jackhammer10.gif"];
var curHammer=0;
function getHammer() {
if (curHammer < hammer.length) {
document.getElementById("jack").src= "poses/" + hammer[curHammer];
curHammer = curHammer + 1;
}
}
setTimeout("getHammer()", 5000);
The big missing element is that you need to call getElementById("jack") to get a reference to the DOM Image so that you can change it's source. If you're using jQuery or most other JS frameworks, just type $("#jack") to accomplish the same.
I don't understand the need for the for loop at all, just increment the index value [curHammer] each time you click, and reset if it passes your max index length (in this case 11).
Pseudo-Code:
currentHammer = -1
hammers = [ "a1.jpg", "a2.jpg", "a3.jpg"]
getHammer()
{
currentHammer = currentHammer + 1;
if(currentHammer > 2)
currentHammer = 0;
image.src = hammers[currentHammer];
}
a) are you just trying to show an animated gif? If so, why not use Adobe's Fireworks and merge all those gifs into a single gif?
b) you know that the way you have it the display is going to go crazy overwriting the gif in a circle right?
c) you might want to put a delay (or not). If so, make the load new gif a separate function and set a timeout to it (or an interval).
Also, you are being redundant. How about just changing the src for the image being displayed?:
var jackHammer = new Array();
for (var i=0;i<11;i++) { //pre-loading the images
jackHammer[i] = new image();
jackHammer[i].src = '/poses/jackHammer'+i.toString()+'.gif';
} //remember that "poses" without the "/" will only work if that folder is under the current called page.
for (var i=0;i<11;i++) { //updating the image on
document.getElementById('jhPoses').src = jackHammer[i].src;
}
on the document itself,
< img id='jhPoses' src='1-pixel-transparent.gif' width='x' height='y' alt='poses' border='0' />

Categories

Resources