6

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?

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • Holder is a jQuery plugin? Something else? – the system Feb 16 '13 at 21:23
  • Seems like there is an `add_image` method that could possibly handle this – Explosion Pills Feb 16 '13 at 21:23
  • 1
    ...beware of `{class:'file-name'}`. It'll break in some older browsers. Use `className` or `"class"`. – the system Feb 16 '13 at 21:24
  • @thesystem: holder.js is a standalone library for generating placeholder images. It's used in Twitter Bootstrap. Added link to question. – mpen Feb 16 '13 at 21:25
  • @thesystem: Excellent point about the `class` property. I did run into that before (in IE I think) and it confused the heck out of me. Gave a very misleading error. – mpen Feb 16 '13 at 21:26
  • @ExplosionPills: Reading through the `add_image` src...looks weird. It creates an image element with the source you provde, and then appends it to an element for you.... I don't want it to do the appending, and also it doesn't look like it's running the image generation code on it either. – mpen Feb 16 '13 at 21:28

1 Answers1

8

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/

imsky
  • 3,239
  • 17
  • 16