Cloning in-memory image in JavaScript /jQuery - javascript

This is probably a really simple one but I couldn't find the answer.
I have the following JavaScript/jQuery code where I am trying to create loading messages:
// preload an image to use for dynamic loading icon whenever requested
$(document).ready(function() {
var loadingIcon = document.createElement('img');
loadingIcon.src = '../images/ajax-loader.gif';
window.loadingIcon = loadingIcon; // chache in global var
});
I wanted to cache the image on load so I'm not requesting it each time I want a loading message. Am I actually acheiving this with the above code?
The idea is that there's a lot of dynamic content on the page, and at any time I might have several different loading icons active.
I add the loading icon wherever with:
$('#myElem').appendChild(window.loadingIcon);
This doesn't actually work though, when I try to show a new loading icon, it just moves the previous one, so I can't have more than one on the page at a time.
I'm assuming I need to clone the element?
I tried to wrap the element in a jQuery object to use clone with $(window.loadingIcon).clone() but that didn't work (the function errored).

You could clone the element, yes. But you can just as well create a new <img> element. If the image src has already been loaded by the browser, the image data will be cached and no further network-load will occur. You don't need to cache the element itself to cache the resource it's pointed at.

Try creating the image as a jQuery object:
var $loadingIcon = $('<img src="../images/ajax-loader.gif" />');
And then you should be able to clone it when you need to use it:
$('#myElem').append( $loadingIcon.clone() );

javascript has a native cloneNode method, at least in IE7, which is all I have at the moment. I'm pretty sure it's cross browser.
this should do what you want:
$('#myElem').appendChild(window.loadingIcon.cloneNode());

Related

Clearing a Popup Solely With Javascript (No HTML, All Contents Define Inside the .js File)?

I'm developing a Chrome extension. I need to clear a popup, the usual way I would do that is to change the contents of body to " " with document.getElementsByTagName('body')[0].innerHTML = '';
But I cannot do this because all content is in a javascript file.
I display some images using the following (just with varying images and styling): var img = document.createElement("img"); img.src = "info_screen.png"; img.alt = 'Information Screen'; document.body.appendChild(img);
I need to clear the popup, the issue is that I cannot use the above mentioned method (due to there being a lack of an HTML file). I looked into possibly clearing the contents of the function that included that code yet all I could find was How do I clear the content of a div using JavaScript? and Creating an element that can remove it self? yet neither suit my situation due to one asking to clear the contents of div (I don't even have an html file) and the other being to create an element that removes itself as opposed to a function. I have tried countless times to adapt the second method to function for my use-case yet none seem to succeed. How would I go about clearing the contents of this popup?

Pulling images from an html page in jQuery

I was given a task to pull images from an html page using only jQuery and nothing else.
The html page is a page with a lot of tables and a lot of different png's. In about 400 lines of html, there are about 80 images. My job is to get all of the images with a certain domain to the bottom of the page (the div class="code"> section), so I can then manually go through them to save them.
So far I am able to get the src of all of the images, but I am not sure how to get all of the actual images. I was thinking if I was to save the source in a variable, I could just redirect the each loop to an img tag and feed it the image source. So far it just returns a broken img link, so I think I have the right idea, but not the right code.
Here is my js
$(document).ready(function(){
$("img[src*='tieks']").each(function() { // src* so I only get certain images
imgsrc = this.src;
$(".code").append(imgsrc);
});
});
This is the code section
<div class="code">
<img src=imgsrc>
</div>
Does anyone know how I could tackle this?
If all you want is to clone all the images into one container:
$('.code').append( $("img[src*='tieks']").clone() );
clone() API Docs
The trick is to create a new element and append it to your div or whatever you prefer.
var img = $('<img id="dynamic">'); //Equivalent: $(document.createElement('img'))
img.attr('src', responseObject.imgurl);
img.appendTo('#imagediv');
This is also answered in this thread from where the example above origins: How to create a new img tag with JQuery, with the src and id from a JavaScript object?
you are trying coding is correct.you are taken only image source.If u want to take all the original images and append to div with class 'code',you will try to change
$("img[src*='tieks']").each(function() {
$(".code").append(this);
});
just try it.

Holder.js -- Get back DOM element?

holder.js
I want to dynamically add a placeholder image to my page.
Inserting it like so doesn't work:
$('<li>',{class:'file-item'})
.append($('<img>',{'data-src':'holder.js/150x150'}))
.append($('<span>',{class:'file-name'}).text(file.name))
.appendTo('#file-list');
Because the holder script has already ran and isn't searching for new elements.
We can, however, run it again manually:
Holder.run()
But then it will scan all the elements that are already added.
So...is there way I can get holder.js to create and give me back a DOM element so I can add it manually without re-running the whole thing?
Pass a Node as the images property to Holder.run and you'll be able to run Holder on any individual image. Holder itself doesn't create a DOM element, it just changes the src value.
Code:
var image = $("<img>").attr({
"data-src": "holder.js/300x200"
})
Holder.run({
images: image[0]
});
image.appendTo("body");
Live example here: http://jsfiddle.net/imsky/p3DMa/

images created dynamically do not appear on screen! -> Javascript

I'm trying to do something simple to practice my Javascript (which I learned some recently) and I'm trying to do a game on it (pacman to be precise).
I am trying to build that game board on the browser by creating images dynamically. I've done an array like this:
var images= new Array(25);
for(i=0;i<25;i++)
images[i]= new Array(25);
And, for the game board I used a matrix done with 0 and 1's with 25x25 size (not going to post it here cause is too big and would make my text hard to read) called board.
For the images that I am using right now I have something like this:
var image_empty = new Image();
image_empty.src="Images/empty.jpg";
var image_wall = new Image();
image_wall.src="Images/wall.jpg";
For the initialization function I have something like this:
function drawField()
{
for(i=0;i<board.length;i++)
{
for(j=0;j<board[i].length;j++)
{
if(board[i][j] == 0)
draw(i,j,image_empty);
else if(board[i][j] == 1)
draw(i,j,image_wall);
}
}
}
And for drawing the images themselves I am using this:
function draw(x,y,img)
{
images[x][y] = new Image(22,22);
images[x][y].src = img.src;
images[x][y].style.position = 'absolute';
images[x][y].style.left = 40+x*22;
images[x][y].style.top = 40+y*22;
}
Every time I run this code nothing appears on the screen. I've tried several times use a load of things but nothing happens. I am saving the pictures (at least I think I am) and still nothing.
Can someone give me some pointers of what could be wrong?
PS: Some people pointed me out using the appendChild method would solve the problem, still, since pacman will be moving around I can't use it to store my images (and I was planning to use the draw function to draw anything).
And btw nor Web Developer plugin or firebug point out errors (the code is correct from their perspective).
Creating an Image in the method you describe doesn't actually display the image. Even putting attributes and styling to make it appear a certain way doesn't add it to the DOM. The advice about append child is correct. For example, if you had:
<div id="main"></div>
and you called
document.getElementById("main").appendChild(images[x][y]);
this would insert the image inside the div. You could do this repeatedly to generate the equivalent of...
<div id="main">
<img src... />
<img src... />
...and so on
</div>
Then, your CSS styling and positioning would work.
There's nothing wrong with your script, but Firebug does display a rendered version of the DOM. As you run the script, you will actually see the HTML tab of Firebug changing with the images you've added to the page.
Also, keep in mind that the DOM must complete loading before you are able to run this. You can accomplish this by doing a simple:
<body onload="drawImages()">
UPDATE: Once you've actually added the 25x25 images, the array still references the elements - they're just now part of the DOM. So, you can change their source via:
images[x][y].src = "newImage.jpg";
If you, for some reason, wanted to remove an image from the board, leaving a gap, you can remove it from the DOM
document.getElementById("main").removeChild(images[x][y]);
or just hide it via CSS.

Appending to InnerHtml without rest of contents flicking

I have a div element with some formatted images. On user request, I load additional images asynchronously, without postback, and append the result (formatted HTML for new images) to the div element using JavaScript:
function onRequestComplete(result) {
var images = document.getElementById('images');
images.InnerHtml += result;
}
All is okay, except that part when images in the panel loaded previously flicker after the HTML is appended. As far I understand, the panel is reconstructed, not just new HTML is appended to its bottom. So it isn't web 2.0 behavior.
How can it be done without flicking? Thanks in advance.
Use the dom method of adding them:
var div = document.createElement('div');
div.innerHTML= result;
document.getElementById('images').appendChild(div);
Or if you really want to do it the right way, create an dom element for each image and then append them. This also has the benefit of preloading the images.
Or just use jQuery. ;)
Using the += operator is the same as:
images.innerHTML = images.innerHTML + result;
Which will re-render all your container, thus causing "flickering".
You should be able to have the same result appending new elements to the container, without having the flickering. For that, you will need the createElement and appendChild methods.
HTH!
When you append your content, you could tack on something like
<span class='endMarker'></span>
Then instead of just updating "innerHTML" like that, you'd look through the DOM inside the target, find the last <span> with class "endMarker", and then append new content after that. Without meaning to be a "use jQuery problem solved" person I will say that a library like that would make things a little easier. To append the content, you could drop it in a hidden div and then move it.
Make all images a single image, than use CSS positioning to show the desired section. The flickering is due to the loading of the new images.

Categories