Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I'm creating a dynamic popup menu whose contents depends on the state of what the user clicked on. Is it considered a better practice to create a template menu in html and modify which options are displayed in javascript, or to create everything in javascript on the fly? I'm using jQuery.

code example:

HTML:

<div id="menuTemplate" class="menu">
  <div class="opt1">Option 1</div>
  <div class="opt2">Option 2</div>
</div>
...

Javascript:

showMenu = function (state) {
  var menu = $("#menuTemplate").clone(true).removeAttr("id");
  if (state) {
    menu.find(".opt1").show();
    menu.find(".opt2").hide();
  }
  // the rest of the function
}

or

Javascript:

showMenu = function (state) {
  var menu = $("<div class='menu'></div>");
  if (state) {
    menu.append($("<div class='opt1'>Option 1</div>"));
  } else {
    menu.append($("<div class='opt2'>Option 2>/div>"));
  }
  // the rest of the function
}
share|improve this question
    
You can do this entirely in CSS. –  Boris Yankov Nov 8 '11 at 21:31
add comment

1 Answer

up vote 2 down vote accepted

It depends upon the requirement: if the options are going to be limited then I would suggest going with show/hide functionality, but if in the future these values require an asynchronous request then refactoring it will be painful.

Moreover, in the second code sample, please don't append entire html in menu: create a div element and add css class to it. This way it is more readable and maintainable. for eg

newdiv = document.createElement('div');
newdiv.className = 'cssClass';
menu.append(newdiv);
share|improve this answer
    
Ah, good call on creating the div element and adding css to it. Thanks! –  stinkycheeseman Nov 8 '11 at 15:18
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.