One thing I don't like about writing javascript-based applications is that you have to put a lot of HTML code in Javascript to render new content. Is there a way I can split this up? I find it messy and bloated to combine them in the same javascript code.
-
why not use AJAX to retrieve the new content server-side?bcosca– bcosca2010-11-27 04:27:25 +00:00Commented Nov 27, 2010 at 4:27
-
that's what I'm doing, but then you need to code the HTML for it, no? Or are you talking about sending the HTML content itself?egervari– egervari2010-11-27 04:29:20 +00:00Commented Nov 27, 2010 at 4:29
-
You certainly can send the HTML content back from an AJAX request and just insert it where you want.Devin Ceartas– Devin Ceartas2010-11-27 04:33:23 +00:00Commented Nov 27, 2010 at 4:33
Add a comment
|
4 Answers
You should check out jQuery's Template plugin, it might be helpful depending on what your creating.
1 Comment
egervari
this looks interesting too... and i can put the html code in the html file, which makes a lot of sense. thanks for this. i'll play with this as well since I am also using jquery anyway.
May be I cannot understand the question but you can put javascript in the separate file:
<script type="text/javascript" src="some.js"></script>
And you can use jQuery which gives you another abstraction level under HTML:
$('div.button').animate({left: 650, height: 38}, 'slow');
4 Comments
egervari
I know this. The problem is that you have stuff happen and you need to create an entire <tr>...</tr> that contains a TON of html code. This is messy to do with string concatenations.
John K
+1 I agree this is the simple and clean approach for any kind of JavaScript separation whether it's jQuery or not.
John K
@egervari: You don't need to concatenate strings - you can build out elements in the DOM dynamically using methods like
document.createElement: developer.mozilla.org/en/DOM/document.createElement I think before getting into the mindset of separating JavaScript from HTML, you first need to get out of the mindset of string concatenation if you don't think it's clean enough. There are other options. jQuery and other frameworks contain ways to build your HTML doc without concatenating strings.egervari
I know I can create nodes like this, but this is also bloated though. I am seriously talking about creating 5-7 nested html tags with many child nodes. These cannot be added to the document pre-emptively - they need to be created via javascript. Using any XML node-based api is still going to be bloated.
I often use a hidden div with prepared HTML which serves like a sample. Then in JS I just take a copy of this HTML-piece and insert the dynamic values.
IMHO, it's convenient because all samples are stored together inside HTML file, and JS code doesn't have to know much about it's structure.