Search code examples
javascriptjqueryhtmltooltip

Creating and Passing HTML in Javascript


I am using a javascript tooltip constructor that allows HTML as part of its content. I want write a helper function that returns an object representing the HTML (as the exact HTML will depend on the constructor input parameter). How can I do this? (The pseudo code is something like this:

function makeHTML(data1, data2){
   var HTML = ""
   if (property holds){
      add the following to the HTML:
           "<br>" +
           "<b>" + "Constant " + "</b>" +  "<br>" +
           "<b>" + varibale + "! " + "</b>" + moredata1 +
           "<br>"
   }
   if (another property holds){
      add the following to the HTML:
           "<br>" +
           "<b>" + "Constant2 " + "</b>" +  "<br>" +
           "<b>" + varibale2 + "! " + "</b>" + moredata2 +
           "<br>"
   }

). I am running into problems trying to return the tags and quotes in general.

When I am filling the content of the tooltip without dynamically created HTML, the proper formatting has tags in quotes (e.g " "):

return {
      title: information
      content:
        "<br>" + 
        data[9] + variable + "<br>"

} Now, I want to make it so that before the return, I can call makeHTML and write:

var dynamicHTML = makeHTML(data1, data2)
return {
  title: information
  content: dynamicHTML
}

Solution

  • You could create an Object that accepts data before outputing ex:

    function dynamicElement(){
        var self = this, html = "";
    
        self.setProp = function(props){
            for(prop in props){
                html += "<p>"+prop+"</p>";
            }
        }
    
        self.draw(where){
            where.innerHtml = html;
        }
    
        return self;
    }
    
    //Usage
    var x = new dynamicElement();
    
    x.setProp([1,2,3]);
    x.draw(document.body);