Wrap It Up - Lazy Man’s HTML Generation With jQuery
29 May 2006 | Tutorials | 24 Comments
The Memorial Day weekend is coming to a close - I’ve been away from the computer for almost 48 hours (gasp!) and I want to get another jQuery tutorial up and online quickly.
I’m dying to do the write up for “Edit In Place the Jquery Way” and “Multiple File Upload Magic” but the code for both is a little more in depth and it just feels like I should tackle a few of the easier tutorials in the beginning.
So here goes -
Ever since making the switch away from table layouts for my websites in favor of all CSS (it must be two and a half years or more now) I’ve been consuming all the information I can find on the subject.
Way back in May of 2004 (ancient history) A List Apart had a great tutorial on creating drop shadows (Onion Skinned Drop Shadows) for any image, regardless of size.
The comments for the article are no longer available, but some of them echoed the sentiment from the editor’s note at the beginning of the tutorial.
Editor’s Note: The techniques demonstrated in this tutorial are not for everyone. The design method works its magic by nesting divs that have no semantic or structural value. If that bothers you (and there are good reasons why it might), this is not the tutorial for you.
(Emphasis added by Jack)
The Problem
Some CSS techniques require “extraneous” markup because currently only one background image can be assigned per element.
For example:
Here is the html code used in the A List Apart tutorial:
<div class="wrap1"> <div class="wrap2"> <div class="wrap3"> <img src="object.gif" alt="The object casting a shadow" /> </div>< </div> </div>
All of those divs serve as “hooks” for background images that make up the drop shadow.
Woudn’t it be nice if we could trim down our source code to:
<img src="object.gif" class="dropshadow" alt="The object casting a shadow" />
Which leads us to…
The Goal
I’m going to show you how easy it is to remove extraneous markup from your html source code using jQuery. Using this method will keep your code cleaner and (more importantly) will make it future layout changes much easier.
The Solution
Here’s how jQuery attacks the problem.
$(document).ready(function(){
$("img.dropshadow")
.wrap("<div class='wrap1'><div class='wrap2'>" +
"<div class='wrap3'></div></div></div>");
});
And then the images would be styled like so:
<img src="object.gif" class="dropshadow" alt="The object casting a shadow" />
A Closer Look
$(document).ready() is jQuery’s version of window.onload()
$(”img.dropshadow”) tells jQuery to find all images with the class name “dropshadow”. If you wanted to use an id instead, you could do something like $(”img#dropshadow”)
wrap() tells jQuery to use the DOM (Document Object Method Model) to wrap the images with the class=”dropshadow” in the html inside the parenthesis.
The End Result
Silly picture… but it’s the same one used in the original Onion Skinned Drop Shadows:
Compare jQuery to Other Solutions
From the jQuery site there’s a link to the Ajaxian website where another javascript library was used to create the Onion Skin Drop Shadow with javascript and I think the amount of code and the complexity of the code speaks for itself. Personally, I would prefer jQuery (but you already guessed that, didn’t you?)
To be fair… no one library is perfect for every job or every coder. This tutorial really isn’t meant to prove that jQuery is the “One True” all purpose javascript library.
Try Prototype, Scriptaculous, YUI, Rico, Behaviour, Moo.fx and the dozens of others. If you find one that works better for you… then use it.
jQuery is a tool that spoke to me. I hope this tutorial has shown you one more useful way to use it.
Related jQuery Tools
jQuery makes it incredibly easy to manipulate the html generated by your visitor’s browser.
You should take a moment and see what you can do with jQuery using append(), prepend(), before(), after(), html(), and remove().
Meatier Tutorials On the Way
For degree of difficulty, today I scored a one or a two. But that’s okay because even though the concept is simple, it’s applicable to lots of situations you come across in your design and coding work.
And besides, regardless of when you read this tutorial, I posted it after a Memorial Day of fun in the sun on the beaches of Florida. I just put the family to bed and I still have sand on my feet.
Rest assured, before we get to the end of the 15 Days of jQuery you’re going to see some more advanced tutorials, examples, and code.
Technorati Tags: jQuery, javascript, DOM, drop shadow
Subscribe
24 Comments
Leave a Reply
You can follow the discussion through the Comments feed. You can also pingback or trackback from your own site.






In the paragraph “The Solution” you write:
“And then the images would be styled like so:
”
Shouldn’t you add a ‘class=”dropshadow”‘ in the img-tag?!
Aye, no way to edit comments … I think you’re missing the ‘class=”dropshadow”‘ in the img-tag one paragraph above too. Thx
Iko,
Good catch on your part… stupid oversight on mine.
Both fixed. Thanks.
Hi Jack,
in the “A Closer Look” paragraph you wrote:
> you could do something like $(”img#dropshadow”)
This is something I see too often. When referencing an ID (”#xyz”) with CSS syntax, its always redundant to put selectors in front of the ID. An ID must be unique, so it can not be specified any uniquer.
I like your tutorials (as I like JQuery), so please keep them clean
@Jorn,
I’m glad you pointed this out. However, I’m going to leave it as is in the tutorial for two reasons:
1- So others can see what to what you are refering
2- Even though your suggestion makes the code more concise, my syntax is not incorrect.
As an analogy… I’ve shown readers how jQuery lets you “chain” methods together and make the javascript very small, clean, and concise. But if you choose not to chain them, and write out each instruction long hand, you don’t get negative points… it still works.
Just to be clear: I agree with your point but disagree on the importance.
In the demo, the image doesn’t show up.
Mary,
Apparently the third party site took the demo down. I’ll try to get a new one back up for you.
Great series. Thanks.
Is there any significance to the way you concatenated the strings in
.wrap(”" etc.?
It seems more logical to break them where you separate the opening tag from the closing tag.
Thom… no significance.
Hi Jack,
I know this is probably a silly question, but do you see any reason why this wouldnt work if the image was nested in a link? I’ve tried implementing this on a gallery i am working on and though its painfully simple it just doesnt seem to want to work. I have assigned a class of dropshadow to all the images, inserted the js as like the examle, checked that the jquery src link is above the js call and still nada.
Any ideas would be greatly appreciated!
Thanks,
Chris
I use Firebug and Web Developer extensions for Firefox to troubleshoot. The first can give me a quick alert to goofs in my code, the second lets me view generated source, not just actual xhtml. In other words, it should show you some of the jQuery generated html.
If you’re nesting the image inside a link, I would think you’d want to target the link (instead of the image) for wrapping with the divs.
Let me know what you find.
Just a note re the uniqueness of css hash notation for IDs. If a CSS script is used on multiple pages or a dynamic system, it is possible that an image could share an ID with , for example, a form input ID on a different page.
ie input#unique and img#unique
Therefore, it is not always redundand if you use CSS on more then one DOM - and you should
It is unlikely, but definitely possible for IDs to match across multiple pages, especially if you have dynamic content.
The demo is 404
A downside of linking out to other sites for a demo. I’ll put one up on this site.
where is the demo!!!!!
Right here:
http://15daysofjquery.com/examples/osds/
Cool solution. No technique in itself is perfect but I think that if you already use jquery for something else on the same site, it’s very easy to use it for fancy dropshadows as well using your technique.
Great tutorials, thanks.
A small detail but important to notice: DOM = Document Object Model, not Method
@Alexis,
Oof… you’re right! I’ll correct that silly mistake now.
Hi,
What if I wanted to get the width of the image (and the width attribute is not set in the html) and then set the width of my wrapper div accordingly? I’m thinking of a caption type situation. Also, what if my images did not have a class (i’m allowing users to upload images), but I wanted to find all images in a particular div, say a content area which does have an id or class?
Thanks,
Scott
Scott,
Getting the width of an image server side with PHP or similar is easy. You can easily pass that info into your html/js.
As for the width of the div, you should at least test setting the width of the div to be less than your images, and the div should expand to contain the image, regardless of the width. A bit of a hack, but might work for you.
As for images without a class, since you’re receiving uploads, you have to be using a server side language to save and process. You could easily add a class using the same server side code. Or, if you knew the parent of the image, or it’s order in the document you could use jQuery to target the nth image.
Finding all images in a particular div is easy:
$(’div#foo img’).each(function(){ alert(’function goes here’); });
[…] http://15daysofjquery.com/wrap-it-up-lazy-mans-html-generation-with-jquery/10/ 1. Insert this code between the html tags in your header or template (header.php in Wordpress). Note: You may already have jquery installed as part of your template or plugin. Try looking in /wp-includes/js/jquery/ $(document).ready(function(){ $(”img.dropshadow-right”) .wrap(” ” + “ […]
[…] config and maintenance and I decided to combine Segio’s CSS only solution with a slighly more complex Javascript solution that would in the end be a bit simpler to implement and […]
I am sorry but I keep getting this error: $(”img.dropshadow”) has no properties. Please help, I thought this might be occurring because the element hasn’t been created yet. Is that a correct assessment. The code is included in the head of the page and is a callback of the ready method just as you instructed. this is what I have in the head of the code: $(document).ready(function(){
$(”img.dropshadow”).wrap(”" + “”);
}); any pointers please?