How to change the src of a img with its alt? - javascript

Is there way to change the image src attribute with its alt attribute on load of the image?
I want the script to automatically change the image's source to the image's alt.
Before
<img src="" alt="exe">
After
<img src="exe" alt="exe">

You could use JavaScript:
// Execute function on load through self-invocation
var switchAlt = function() {
// Get all images on the document
var images = document.getElementsByTagName('img');
// Count the number of image elements and switch alt and src
var i = images.length;
while (i--) {
images[i].src = images[i].alt;
}
}();
Don't forget to wrap it into script tags if you're implementing it in HTML files:
<script type="text/javascript">
// Execute function on load through self-invocation
var switchAlt = function() {
// Get all images on the document
var images = document.getElementsByTagName('img');
// Count the number of image elements and switch alt and src
var i = images.length;
while (i--) {
images[i].src = images[i].alt;
}
}();
</script>

Try this:
var change = function() {
var imgs = document.images || document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].src = imgs[i].alt;
}
}
DEMO

First of all, give the id of the image so img tag will look like this:
<img id="img1" src="" alt="myimage.jpg" onload = "changesource()"/>
Now write a JavaScript function like this:
function changeSrc()
{
var img = document.getElementById("img1");
img.src =img.alt;
}
Now call this function on the load of image like this:
onload = "changeSrc()"

Related

Check if an error was thrown when loading an image during page startup

I am trying to write a JS script that will look through the page when it loads to see if any images had an error loading, and to change the src of that image to a default image. What I was trying to do was to loop through all the list of images returned from document.images, and to check every image to see if it finished loading using image[i].complete, and if it didn't, then change the src of that image to the default link. It did not work for me, and I can't think of the solution.
window.onload = function() {
var images = document.images;
for (var i = 0; i < images.length; i++) {
if (!image[i].complete) {
images[i].src = 'assets/default-avatar.jpg';
}
}
}
The solution is to use the error event on IMG tags:
<img src="..." onerror="this.src = 'default_image_url';">
Because complete returns true even if the image couldn't be loaded (at least in some browsers), you could use naturalWidth. If no image is loaded naturalWidth is 0.
window.onload = function() {
var images = document.images;
for (var i = 0; i < images.length; i++) {
if (image[i].naturalWidth === 0) {
images[i].src = 'assets/default-avatar.jpg';
}
}
}

Image array for javascript slideshow not appearing

I'm making a slideshow in javascript for a class assignment and I have the slideshow working but it's not displaying the images. I can see that the image icon changes but the actual image is not showing.
<script type="text/javascript">
//put images in array
var pics = new Array();
pics[0] = new Image();
pics[0].src = "images/forest.jpg";
pics[1] = new Image();
pics[1].src = "images/mountains.jpg";
pics[2] = new Image();
pics[2].src = "images/nature.jpg";
pics[3] = new Image();
pics[3].src = "images/snowtops.jpg";
var index = 0; //start point
var piclength = pics.length - 1;
function slideshow() {
document.slide.src = pics[index];
if (index < piclength) {
index++;
}
else {
index = 0;
}
}
function slide() {
setInterval(slideshow, 3000);
}
</script>
<body onload="slide()">
<h1>Nature Photography</h1>
<main>
<section>
<p>I am an enthusiastic about nature photography. Here is a slideshow of my
works.</p>
<aside> <img id="myImage" src="images/forest.jpg" name="slide" width="95%">
</aside>
First, I would put the script tag after your HTML. This will allow you to cache DOM elements without waiting for the "DOMContentLoaded" event or the "load" (window) event to be fired.
Second, you should cache the "myImage" element. Something like const slider = document.getElementById('myImage').
Third, check your console. Maybe your image URLs are wrong? And make sure your HTML is valid. From what you posted, you are missing a lot of things (doctype, html/head tags, you didn't close body tag and similar)

Assign array of image elements to DOM ids

I have an array of URIs that represent .png elements, e.g., "./img/diamond-red-solid-1.png".
I want to assign each element of the array "gameDeck[0], gameDeck[1], etc. to div ids in HTML. Do I need to identify the elements as = SRC.IMG?
var gameDeck[];
var gameBoardCards = function () {
for (let cardArr of cardsToLoad)
gameDeck.push("./img/" + cardArr + ".png");
}
gameBoardCards();
document.addEventListener('DOM Content Loaded', function () {
gameDeck[0] = document.getElementById("card1");
gameDeck[1] = document.getElementById("card2");
etc.
});
The way I'm understanding your question is that you would like to target the divs in your HTML with ids of card1, card2, card3... card12 etc.
You would like to insert an img tag into each of these divs with the src being the URIs of the gameDeck array.
The following code achieves this. I've tested it and it works fine. Hope it helps :)
document.addEventListener('DOMContentLoaded', function () {
//iterate through the gameDeck array.
for (let x = 0;x < gameDeck.length;x++){
//create an img tag for each gameDeck element
var imgElement = document.createElement("img");
//set the source of the img tag to be the current gameDeck element (which will be a URI of a png file)
imgElement.src = gameDeck[x];
//target the div with id "card(x + 1)"
var cardID = "card" + (x + 1);
var cardElement = document.getElementById(cardID);
//append the img tag to the card element
cardElement.appendChild(imgElement);
}
//log the HTML to the console to check it
console.log(document.getElementById('body').innerHTML);
});
Here is a way that you can either insert images as background images, or as <img /> elements into the divs you are referring to:
<div id="card0" style="width: 100px; height: 100px;"></div>
<div id="card1" style="width: 100px; height: 100px;"></div>
let loadedImage = [];
function preloadImages(urls, allImagesLoadedCallback) {
let loadedCounter = 0;
let toBeLoadedNumber = urls.length;
urls.forEach(function(url) {
preloadImage(url, function() {
loadedCounter++;
console.log(`Number of loaded images: ${loadedCounter}`);
if (loadedCounter == toBeLoadedNumber) {
allImagesLoadedCallback();
}
});
});
function preloadImage(url, anImageLoadedCallback) {
img = new Image();
img.src = url;
img.onload = anImageLoadedCallback;
loadedImage.push(img);
}
}
function gameBoardCards() {
for (let i = 0; i < loadedImage.length; i++) {
document.getElementById(`card${i}`).style.backgroundImage = `url('${loadedImage[i].src}')`;
// document.getElementById(`card${i}`).appendChild(loadedImage[i]);
}
}
preloadImages([
`https://upload.wikimedia.org/wikipedia/commons/thumb/7/7d/Color_icon_green.svg/2000px-Color_icon_green.svg.png`, `https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Solid_blue.svg/225px-Solid_blue.svg.png`
], function() {
console.log(`all images were loaded`);
gameBoardCards();
// continue your code
});
It may seem like a bit much for what you are trying to accomplish, but I threw in a proper image-loading handler there. The preloadImages function will handle the loading of images, that way they are properly preloaded, and can render to the DOM. Often times, we try to use images before they are properly loaded, resulting in them sometimes not being displayed, despite no errors are being thrown.
The rest of the code is straight forward, in the for loop, it loops through the existing divs and you can either use the current active line document.getElementById(`card${i}`).style.backgroundImage = `url('${loadedImage[i].src}')`; to use the loadedImage[i] image src to load that as the divs's background image. Or you can use the commented-out line directly below that document.getElementById(`card${i}`).appendChild(loadedImage[i]); to insert an <img /> element into that div. Just use either one that works for you.
You can see the code in action in this JS Fiddle demo.
Hope this helps :)

Javascript replacing image source

I am trying to change the contents of the src tag within a web page (without changing the HTML/naming structure)
My code looks something like this at the moment:
....
<div class="main">
<button>
<img src="image/placeHolder.png"/>
<div>the nothing</div>
</button>
</div>
....
I need to change the src of this img tag
My javascript looks like this at the moment
....
<script type="text/javascript">
function changeSource() {
var image = document.querySelectorAll("img");
var source = image.getAttribute("src").replace("placeHolder.png", "01.png");
image.setAttribute("src", source);
}
changeSource();
</script>
....
I have no idea why it isn't working but I'm hoping someone out there does :D
Change your function to:
function changeSource() {
var image = document.querySelectorAll("img")[0];
var source = image.src = image.src.replace("placeholder.png","01.png");
}
changeSource();
querySelectorAll returns an array. I took the first one by doing [0].
But you should use document.getElementById('id of img here') to target a specific <img>
If you want to target all <img> that has placeholder.png.
function changeSourceAll() {
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
if (images[i].src.indexOf('placeholder.png') !== -1) {
images[i].src = images[i].src.replace("placeholder.png", "01.png");
}
}
}
changeSourceAll();
function changeSource() {
var img = document.getElementsByTagName('img')[0];
img.setAttribute('src', img.getAttribute('src').replace("placeHolder.png", "image.png"));
}

Javascript will not load the pictures

I want to load these banner.png files to the screen but all it prints out is the actual text from the banner array?
function randImg(){
var banner = new Array();
banner[0] = 'banner1.png';
banner[1] = 'banner2.png';
banner[2] = 'banner3.png';
maxImg = banner.length;
randNum = Math.floor(Math.random()*maxImg);
return banner[randNum];
}
any thoughts? I think I need to some how add a src but I am not sure how.
Might be too obvious, but...
function randImg(){
var banner = new Array();
banner[0] = 'banner1.png';
banner[1] = 'banner2.png';
banner[2] = 'banner3.png';
maxImg = banner.length;
randNum = Math.floor(Math.random()*maxImg);
return '<img src="' + banner[randNum] + '" />';
}
Demo: http://jsfiddle.net/AlienWebguy/u7yfq/
My pure javascript DOM manipulation is a little fuzzy (usually use jquery) but something like this should do the trick:
<div id="images"></div>
<script type="text/javascript">
function randImg(){
var banner = new Array();
banner[0] = 'banner1.png';
banner[1] = 'banner2.png';
banner[2] = 'banner3.png';
maxImg = banner.length;
randNum = Math.floor(Math.random()*maxImg);
var container = document.getElementById('images');
var img = document.createElement('img');
img.setAttribute('src',banner[randNum]);
container.appendChild(img);
}
</script>
The instruction that loads the image should be like this.
Where imgElement is an IMG element.
imgElement.src = randImg();
If you don’t know how to get an IMG element. Give the IMG element an ID attribute and load this like this.
For an IMG element as <img id="myImage" src="" />
Then:
var imgElement = document.getElementById("myImage");
imgElement.src = randImg();
Note.- my answer gives instruction on how to change the source of an IMG element that exists in the DOM (It is recommended to do so). You should NEVER document.write() an element, Neither on demand or when page is loading. That practice has been deprecated and many browsers would delete the whole page contents if you do so.

Categories