How do I encode HTML characters within Javascript functions?

882 views Asked by At

to all Javascript experts this question might be just basics. I'm using jQuery and I am working on a tooltip created with jQuery.flot.

The following is a part of my javascript function within an html file and this is exactly what I need to have the tooltip div to be rendered correctly:

$('<div id="tooltip">' + contents + '</div>').css( {

Because the div is not shown I used Firebug to look for the reason and the line of code from above shows the special characters < and > encoded as html entities < and > as you can see here:

$('&lt;div id="tooltip"&gt;' + contents + '&lt;/div&gt;').css( {

I was searching several online sources for a solution and tried things like .replace(/lt;/g,'<') or .html().text() and it took me more than three hours but nothing was helpful.

I works fine on localhost.

Full Source Code:

<script language="javascript" type="text/javascript" src="../JavaScript/flot/jquery.js"></script>
<script language="javascript" type="text/javascript" src="../JavaScript/flot/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="../JavaScript/flot/jquery.flot.categories.js"></script>
<![CDATA[
  <script type="text/javascript">

    $(function () {
      var data = [ ]]>{e1Array}<![CDATA[ ];
      $.plot($("#placeholder1"), [ data ], {
        series: {
          bars: {
            show: true,
            barWidth: 1,
            align: "center"
          }
        },
        grid: {
          hoverable: true,
          clickable: true
        },
        xaxis: {
          mode: "categories",
          tickLength: 0
        },
        yaxis: {
          min: 0,
          max: 1,
          ticks: 0
        }
      } );
    });

    var previousPoint = null;
    $("#placeholder1").bind("plothover", function (event, pos, item) {
      if (item) {
        if (previousPoint != item.datapoint) {
          previousPoint = item.datapoint;
          $("#tooltip1").remove();
          showTooltip(item.pageX, item.screenY, item.series.data[item.dataIndex][0] + ': ' + item.series.data[item.dataIndex][1] + ' Einträge');
        }
      } else {
        $("#tooltip1").remove();
        previousPoint = null;
      }
    });

    function showTooltip(x, y, contents) {
      $('<div id="tooltip">' + contents + '</div>').css( {
        position: 'absolute',
        display: 'none',
        top: 100,
        left: x,
        border: '1px solid #fdd',
        padding: '2px',
        'background-color': '#fee',
        opacity: 0.80
      }).appendTo("#e1-container").fadeIn(0);
    }

  </script>
]]>
<div class="e1-container" id="e1-container">
  <div id="placeholder1" class="e1"></div>
</div>
3

There are 3 answers

2
pid On BEST ANSWER

You use appendTo(), which is fine. You append the node only when the plothover flot event is fired. This is correct, too. So your code looks fine, you should probably look into this:

Jquery Flot "plothover" event not working

EDIT: You also can put the JS <script> after the HTML.

2
Alexis Paques On

Do not directly add the contents inside the selector.

1) Create your DOM : var k = $('<div id="tooltip"></div>');

2) Fill your DOM :

// Add after
k.append(contents);
// Replace 
k.html(contents);
// Replace and the content is just some text
k.text(contents);

3) Set the CSS : k.css({ ... })

4) Add the DOM to your page k.appendTo('#container');. You can also use $('#container').html(k); to replace the container contents and avoid to have a duplicate

In short :

var k = $('<div id="tooltip"></div>')
        .append(contents)
        .css({})
        .appendTo('#container');

NOTE: The best way is to already create your tooltip div and just fill the elements to avoid to create two div with same ID, ... If you are afraid it perturbs the page, add display : none; to the CSS before to edit it, then change the classes when you edit it.

You will need to create div on 2 conditions :

  • The pages is created on load with variable number of components
  • You want to dynamically load CSS or JS.
2
Bergi On
<![CDATA[
  <script type="text/javascript">

This seems to be your problem, or at least the reason why FireBug does show html entities in your code. If you want to use cdata at all, you should place it inside of the <script> tags.

On why the tooltip is not shown at all, I can only guess, but for text content I'd recommend to use

$('<div id="tooltip"></div>').text(contents)

instead of using it as a html string.