views:

926

answers:

3

What's the best way to load HTML markup for a custom jQuery UI widget?

So far, I've seen elements simply created using strings (i.e. $(...).wrap('<div></div>')) which is fine for something simple. However, this makes it extremely difficult to modify later for more complex elements.

This seems like a fairly common problem, but I also know that the jQuery UI library is new enough that there may not be a widely accepted solution for this. Any ideas?

+6  A: 

Something which is quite neat to do is this:

var newDiv = $("<div></div>"); //Create a new element and save a reference
newDiv.attr("id","someid").appendTo("body");

That way, you are creating an element, and storing its reference in a variable, for later use.

Andreas Grech
Good answer! Its worth considering also that DOM manipulation can be costly, so its worth trying to render load all your HTML before attempting any manipulation. There is also a convention to prefix any jQuery variables with a $. So newDiv would become $newDiv. This helps distinguish between jQuery and non jQuery variables.
James Wiseman
A: 

A lot of times for really complex templates i'll just store the html blocks as strings in JSON objects for later access ... eg:

var temp = {
  header : "<div class='foo'><h3>{HEADER}</h3></div>",
  content : "<div class='bar'><p>{COPY}</p></div>"
}

And then just perform some replacement on those when things come back. That way the markup is separated somewhat from the logic to load the data, so swapping out templates etc can be a little quicker.

var text = "I am the header text";
var head = new String(temp.header);
$(target).append(head.replace("{HEADER}",text));

Anyway, this approach has worked well for me with AJAX widgets and that sort of thing, where there is a possibility that the design may radically change around.

sparkey0
+1  A: 

If you have a large amount of complex HTML, and don't want to deal with hardcoded strings in your JavaScript code, you can put it in a separate HTML file and use the Ajax load function.

It's chainable, so you can load the HTML file (the whole thing, or a selected fragment), inject it into your current DOM, and keep right on going.

system PAUSE