Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

A popular, efficient method is to output all of your additional markup (whatever you may need later) to the bottom of your page in script tags, so that the markup is not rendered by the browser.

<script type="text/template" id="template-example">
    <!-- All of your markup here -->
    <% // do some JavaScript in here... %>
    <%= echo_this_variable %>
</script>

You can then grab your markup using jQuery...

var markup = $('#template-example').html();

And parse those JS examples I threw in there using a templating engine, such as the one in Underscore.js (which I recommend), or one of the jQuery ones in this answer: jQuery templating engines

Have fun!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top