Set HTML <img> element to Javascript image variable - javascript

I have an array of image variables that get preloaded using javascript to make an image sequence animation. The issue I have is setting the img element from HTML to use one of these images. It seems all the properies are strings?
Here's how I set the array of images in javascript:
for(var i = 0; i < 30; i ++){
anim[i] = new Image();
if(i < 10){
anim[i].src = "images/anim/frame0" + i + ".png";
}
if(i >= 10){
anim[i].src = "images/anim/frame" + i + ".png";
}
}
and I simply have an
^img tag = "animation"^
in html that I want to change.

Your code looks valid.
for(var i = 0; i < 30; i++){
anim[i] = new Image();
if(i < 10){
anim[i].src = `images/anim/frame0${i}.png`;
}
if(i >= 10){
anim[i].src = `images/anim/frame${i}.png`;
}
}
Now you can do:
document.body.appendChild(anim[0]);
I tested this and it works for me.
If you want to change src on the fly then you'd have to select the appended element and update its src like this: document.querySelectorAll('img')[0].src = newSourceVariable;.

Related

Background image changer interval Javascript

I'm new to javascript and I need some help with a function that I am trying to get to run. I would like for the background of my body to change every seconds using the images provided but when I try to run the script it does not seem to work.
Javascript:
var i = 0;
var images = [
URL('file:///Users/BodyDesigns/Documents/Altered%20Images/P1010216.jpg'),
URL('file:///Users/BodyDesigns/Documents/Altered%20Images/P1010217.jpg'),
URL('file:///Users/BodyDesigns/Documents/Altered%20Images/P1010200.jpg')
];
function backgroundChanger() {
for(; i < images.length; i++) {
document.getElementById('background').style.backgroundImage.innerHTML = images[i];
}
}
setInterval( backgroundChanger(), 4000);
html:
<body id="background" onLoad="backgroundChanger()">
This should do the trick.
var i = 0;
var images = [
'https://upload.wikimedia.org/wikipedia/commons/2/23/Screenshot_from_IMAX%C2%AE_3D_movie_Hidden_Universe_showing_the_Helix_Nebula_in_infrared.jpg',
'http://ichef.bbci.co.uk/wwfeatures/wm/live/1280_640/images/live/p0/40/m0/p040m0bc.jpg',
'http://az616578.vo.msecnd.net/files/2016/08/06/636060577940287734-194579614_maxresdefault.jpg'
];
function backgroundChanger() {
if(i >= images.length){
i = 0;
}
document.getElementById('background').style.backgroundImage = 'url(' + images[i++] + ')';
}
setInterval( backgroundChanger, 4000);
As you can see, the url() should be passed inside a string to work. And there is no innerHtml on backgroundImage property.

Javascript - Add images

I have some images (image1, image2, image3 ..etc. ) and I will add those images to each cell seperately. I found a code to insert the images.
document.getElementById("cell1").innerHTML = "<img src='image1.png'>";
Now, Can someone help me to put above code in a loop in order to avoid to write same code for each image ?
I have tried below code but it does not work. Probably there is a problem with quotes. Or is there a better way to insert multiple images to each cells ?
for (x=0; x=10; x++) {
document.getElementById("'cell" + x + "'").innerHTML = "<img src=" + "' + x + ".png'>"; }
for (x=0; x=10; x++) {
document.getElementById("cell" + x).innerHTML = "<img src='image" + x + ".png' />";
}
for (x=0; x=10; x++) {
var img = new Image();
img.src = 'image' + x + '.png';
document.getElementById('cell' + x).appendChild(img);
}
As you may have noticed creating elements from html strings can get really messy really quick.
Its often a a better idea to use document.createElement to create the elements and then manipulate the properties of the element.
img = document.createElement("img");
img.src = "image" + i + ".png"; // image1.png ... etc
Another very useful technique is using document fragments to create ad-hoc collections of elements before we actually attach them to the real document or elements.
frag = document.createDocumentFragment();
frag.appendChild(img);
targetNode.appendChild(fragment); // attach all the images in the fragment
This is good for performance since actually touching the DOM is slow - we don't want to do it over and over in a loop.
Lets take these two techniques and create a function which creates img elements
function createImages(n){
var i, frag, img;
frag = document.createDocumentFragment();
for (i = 0; i < n; i ++) {
img = document.createElement("img");
img.src = "image" + i + ".png"; // image1.png ... etc
frag.appendChild(img);
}
return frag;
}
We could use this function to attach images to each cell in table
var table = document.getElementById('test'),
cells = table.getElementsByTagName('td');
(function(){
var i,
len = cells.length,
images = createImages(3);
for (i = 0; i < len; i++) {
cells[i].appendChild( images.cloneNode(true) );
}
}());

JavaScript increment images

I'm trying to use JavaScript to list images 01-40 in order automatically.
Like this:
<img src="01.jpg" />
<img src="02.jpg" />
<img src="03.jpg" />
<img src="04.jpg" />
<img src="05.jpg" />
...
I don't want to write each img src manually, as I want to use this on multiple pages
I'd like the image starting and ending number to be variables that I can edit easily.
You need the parent element for imgs:
for ( var i = FIRST_NUMBER ; i < LAST_NUMBER ; i++ ) {
var elem = document.createElement("img");
if ( i < 10 ) {
elem.setAttribute("src", "0"+i+".jpg");
} else {
elem.setAttribute("src", i+".jpg");
}
document.getElementById(PARENT_ID).appendChild(elem);
}
function img_create(startIndex, endIndex) {
for (i = startIndex; i <= endIndex; i++) {
var oImg=document.createElement("img");
oImg.setAttribute('src', i+".jpg");
//other attributes you need
document.body.appendChild(oImg);
}
}
Working example: http://jsfiddle.net/Lw3bjcx4/1/
function createImages(count, elementId) {
// Get the container element where you want to create the images
var element = document.getElementById(elementId)
// Loop count times over to create count image elements
for (var i = 0 ; i < count ; i++) {
// Create a new image element
var imageElement = document.createElement('img')
// Set the source to index.jpg where index is 0,1,2,3.... count
imageElement.setAttribute('src', i + ".jpg")
// Append the new image element to the choosen container.
element.appendChild(imageElement)
}
}
// Test to create 10 images.
createImages(10,"imgs")
You can use like this:
var imgdiv = document.getElementById('imgdiv');
var img = imgdiv.getElementsByTagName('img');
for(var i=0;i<40;i++){
img[i].src=i+'.jpg';
}
Here is an alternative to all other answers, where you don't need to use an id to put images in. Just paste the script tag where you need to have the images. For example, if you put it in a div, the script will automatically insert the images in place.
<script type="text/javascript">
var thisScriptNode = document.currentScript;
for(var i = 1 ; i <= 40 ; i++) {
var img = document.createElement("img");
img.src = ("00" + i).substr(-2) + ".jpg";
thisScriptNode.parentNode.insertBefore(img, thisScriptNode);
}
</script>
You can easily change the number of leading zeros. For example, to get numbers with three characters, replace "00" with "000" and -2 with -3.
var to = 10;
var from = 0;
for (i = from; i < to; i++){
var elem = new Element('img', { src: i + '.jpg' });
document.body.appendChild(elem);
}
it will append to <body> images with names from 0.jpg to 9.jpg

Delete Javascript generated HTML

I am programming a blackjack game and for each drawn card i create a tag <img> to display the card.
Naturally i have to delete this tag <img> after every game, but how can i do this?
Is there a way that I can remove all <img> tags within a parent?
Is there something like this: (Pseudecode)
div.removeAllChildElemtens()
or
div.removeChildElements("img");
Thanks.
If you create the elements using document.createElement('img') then you can keep a reference to them in order to delete them later.
var cards = [];
for (var i = 0; i < 52; i++)
{
var card = document.createElement('img');
// ... more initialisation of card
cards.push(card);
}
// later, to remove all
for (var i = 0; i < cards.length; i++)
{
var card = cards[i];
card.parentElement.removeChild(card);
}
Please, see the removeChild usage trick or use the new remove() function:
var div = document.getElementById("parentDivId");
var images = div.getElementsByTagName('img');
for(var i = 0; i < images.length; i++){
var img = images[i];
img.parentNode.removeChild(img);
//OR img.remove() as #Pete TNT pointed-out for modern web-browsers (FF/CH < 23)
}

Replace an image wherever it is used - Javascript

I'm looking for a way to replace an image that could be used anywhere on a page.
So if we have an example html page like this:
<html>
<head>
</head>
<body>
<img id="1" src="example.com/img/1889.png">
<div style="background: url('example.com/img/1889.png')">
<div>
<a>
<img id="2" src="example.com/img/1889.png">
</a>
</body>
</html>
Where ever - example.com/img/1889.png - appears, it must be replaced with something else.
EDIT
Unfortunately I can't use any javascript libraries. Its for a browser plugin. Nor can I use browser specific APIs
There might be some syntax errors here, but basically just try something like:
<script>
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
if (imgs[i].src == "oldImg")
imgs[i].src = "newImg";
}
}
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
if (divs[i].style.backgroundImage == "oldImg")
divs[i].style.backgroundImage = "newImg";
}
}
</script>
The following code does what you're looking for:
var images = document.querySelectorAll('[src]'), // all image and input elements
styled = document.querySelectorAll('[style]'), // all elements with inline style
iLen = images.length,
sLen = styled.length,
url = 'example.com/img/1889.png', // the string you're searching for
str = 'some/string', // replace with whatever you choose
i;
// check for 'example.com/img/1889.png' in image source
for (i = 0; i < iLen; i += 1) {
if (images[i].src.indexOf(url) !== -1) {
images[i].src = str;
}
}
// check for 'example.com/img/1889.png' in either background or background-image
for (i = 0; i < sLen; i += 1) {
if (styled[i].style.backgroundImage.indexOf(url) !== -1) {
styled[i].style.backgroundImage = 'url(' + str + ')';
}
}
Demo

Categories