How do I encode HTML characters within Javascript functions? - javascript

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:
$('<div id="tooltip">' + contents + '</div>').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>

<![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.

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.

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.

Related

Chart js show/hide legend during runtime via buttonClick

Hi i want to show/hide the legend of my linechart (chart.js) by clicking a button.
I tried this so far:
The following code changes the value of scatterChart.legend.options.display but after executing scatterChart.update() the value changes automatically to the initial value!
function showHideLegend() {
console.log(scatterChart.legend.options.display); // -> "inital-value" e.g.: true
if (scatterChart.legend.options.display == true) {
scatterChart.legend.options.display = false;
} else {
scatterChart.legend.options.display = true;
}
console.log(scatterChart.legend.options.display); // -> value successfully changed e.g.: false
scatterChart.update();
//Chart.defaults.global.legend.display = false; // <- does not have an effect
console.log(scatterChart.legend.options.display); // -> "inital-value" e.g.: true
}
function initMap() {
scatterChart = new Chart(document.getElementById("scatterChart"), {
type: 'line',
data: {
/*datasets: [
]
*/
},
showScale: false,
options: {
legend: {
position: 'right',
labels: {
fontSize: 15
}
}
}
});
HTML
<canvas id="scatterChart" style="width: 1920px; height: 1080px; background-image:url('image.jpg'); background-size: 100% 100%;"></canvas>
<div id="scatterLegend"> //howToPutLegendHere??// </div>
<input type="button" value="Show/Hide Legend" onclick="showHideLegend()">
It looks like you were just trying to update the wrong legend config in the chart.js instance object. Here is the correct way.
document.getElementById('hideLEgend').addEventListener('click', function() {
// toggle visibility of legend
myLine.options.legend.display = !myLine.options.legend.display;
myLine.update();
});
The thing that you were trying to update (e.g. chart.legend.options) is just the default legend configuration object. This gets merged with whatever options you define in your chart's options.legend config.
Here is a codepen example showing the legend show/hide behavior from a button click.
You could also opt to not use the built in legend and generate your legend as pure HTML/CSS anywhere on your page, and then use jQuery (or standard javascript) to show and hide. I won't provide an example for the showing/hiding (see jQuery's show/hide functions) but I will demonstrate how to generate a custom legend. First you need to use the options.legendCallback option to create a function that generates the custom legend.
options: {
legend: {
display: false,
position: 'bottom'
},
legendCallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend">');
for (var i = 0; i < chart.data.datasets.length; i++) {
text.push('<li><div class="legendValue"><span style="background-color:' + chart.data.datasets[i].backgroundColor + '"> </span>');
if (chart.data.datasets[i].label) {
text.push('<span class="label">' + chart.data.datasets[i].label + '</span>');
}
text.push('</div></li><div class="clear"></div>');
}
text.push('</ul>');
return text.join('');
}
}
Then use the .generateLegend() prototype method to generate the template (which executes the legendCallback function defined above) and insert it into the DOM.
$('#legend').prepend(mybarChart.generateLegend());
Here is a codepen example that demonstrates the custom legend approach. You can modify the legendCallback function to use whatever HTML you want for the legend structure and then use standard CSS to style it. And finally, use javascript to show/hide it on the button click.
Did you try putting it in a div and hide/show it with CSS? it will be present but hidden and update() will make changes to the existing data so when u want it, just remove class "hidden".

document type does not allow element "h4" here

I can't find out what the problem is with this line of code:
…sc', '<h4 class="vtem_news_show_title">Nesmet El Bouhaira</h4>');$('#vtem1 img…
This is the error message I receive:
**document type does not allow element "h4" here**
What do I need to change?
This is the whole <script>:
<script type="text/javascript">
var vtemnewsshow = jQuery.noConflict();
(function($) {
$(document).ready(function() {
$('#vtem0 img').data('ad-desc', '<h4>Nesmet El Bouhaira</h4>');
$('#vtem1 img').data('ad-desc', '<h4>Tunis Mall 1</h4>');
$('#vtemnewsshowid89-newsshow').adGallery({
loader_image: 'http://laselection-immobiliere.com/modules/mod_vtem_news_show/images/loading.gif',
update_window_hash: false,
start_at_index: 0,
bottompos: 20,
thumb_opacity: 0.8,
animation_speed: 400,
width: '970',
height: '340',
display_next_and_prev: 1,
display_back_and_forward: 0,
slideshow: {
autostart: 1,
speed: 5000
},
effect: 'slide-hori', // or 'slide-vert', 'fade', or 'resize', 'none'
enable_keyboard_move: 1,
link_target: '_self'
});
});
})(jQuery);
</script>
If your Javascript contains HTML tags, a validator considers these part of the document, unless you prefix your code like this:
<script type="text/javascript">
//<![CDATA[
jQuery.data(element, '<h1>Hello, world.</h1>');
//]]>
</script>
You might have come across another way to resolve this issue:
<script type="text/javascript">
jQuery.data(element, '<' + 'h1>Hello, world.<' + '/h1>');
</script>
This basically chops the string to "hide" the tags from a validator. It makes code harder to read and I'd never prefer this "hack" to the CDATA solution.
Please have a look at this question, which is rather old but has a lot of answers.

Google chart: how to make right side of the "white space" empty?

I use Google Chart in order to build some graphichs together with text description.
On the first iteration I used small "title" for each graph type and that was looking well. But at some point I've added total value for each graph... and text started to be wrapped.
Question 1: Is there any way to prevent text wrapping (see the right portion of the chart)?
I've tried put text inside of "..." but Google chart just convert these tags into pure text.
Question 2: Is there any way to move whole graph to the left and consume unused area so the right part will have more space for text?
Any thoughts are welcome! Probably there is any other solution that will work for me?
P.S.
Please see how that looks right now on the screenshot:
P.P.S Here is JS code I use to display the graphs
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/google/jsapi.js"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
var expArray = [<%=ExperienceArray %>];
function drawChart() {
if (expArray.length > 0) {
$('#chart_div').show();
$('#MessagesDiv').hide();
var total = 0, train = 0, match = 0, ageing = 0;
for (var i = 0; i < expArray.length; i++) {
total += expArray[i][1];
train += expArray[i][2];
match += expArray[i][3];
ageing += expArray[i][4];
}
var data = google.visualization.arrayToDataTable([
['№', 'Total (' + total + ')', 'Training (' + train + ')', 'Matches (' + match + ')', 'Ageing (' + ageing + ')']
].concat(expArray));
var options = {
title: 'Gained experience',
allowHtml: 'true',
hAxis: { title: '', titleTextStyle: { color: 'black' } },
colors: ['#00FF00', '#6600CC', '#0000CC', '#000000']
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
} else {
$('#chart_div').hide();
alert("Data are absent");
}
}
</script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
Add the following code (adjust as necessary) to your options: chartArea: {left: 0}
So your options file would become this:
var options = {
title: 'Gained experience',
allowHtml: 'true',
hAxis: { title: '', titleTextStyle: { color: 'black' } },
colors: ['#00FF00', '#6600CC', '#0000CC', '#000000'],
chartArea: {left: 0}
};
Note: the current setting will slice off the entire axis labels, so you want to use something appropriate in size bigger than 0 (you can calculate something with an algorithm, or just fiddle until you have it like you want it).
For the legend, however, there is no trick.
When Google creates the SVG for the chart, it will split the legend in to two lines (two separate SVG text elements) so it's not easy to tweak. You can't very well fix it easily. One option is to create a separate chart with just the legend (and no chart area) which will mimic the legend, and then link the two charts together (if you want click interactivity with the legend).
Alternatively, you can reduce the font size using legend: {textStyle: {fontSize: 8}} or whatever font size will prevent the text from wrapping (again, you can create an algorithm or fiddle with it until it works).
As a separate option, you can create a manual legend and use javascript to mimic click interactivity, and then you can use CSS/Javascript to format it however you want.

HighCharts.JS / General Javascript

I've found a few posts on this but none that have helped me solve the situation. I'll try to explain the best I can.
My HighCharts example code works fine when I put it in an ASP.NET user control and simply browse to a page that contains my user control, as it is simply the same example that comes with the highcharts package. The following code is therefore in an asp.net web user control.
<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="/js/highcharts.js"></script>
<!-- 1a) Optional: add a theme file -->
<!--
<script type="text/javascript" src="/js/themes/gray.js"></script>
-->
<!-- 1b) Optional: the exporting module -->
<script type="text/javascript" src="/js/modules/exporting.js"></script>
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Under / Over 2.5 Goals'
},
tooltip: {
formatter: function () {
return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function () {
return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Under / Over 2.5 Goals',
data: [
['Under', 33.0],
['Over', 67.0]
]
}]
});
});
</script>
<!-- 3. Add the container -->
<div id="container" style="width: 800px; height: 400px; margin: 0 auto">
</div>
When however I am loading this same user control into my page dynamically using AJAX the chart is not rendering and I am getting an empty white as per the inline styling. I am presuming that this is because the JS code is executing when the document is ready and this will not work when I am loading the control dynamically.
The following code resides in an external .js file
Service.GetChartData(OnGetChartDataSuccess, OnGetChartDataFailure);
function OnGetChartDataSuccess(result) {
$get('ChartDataContent').style.display = 'none';
Sys.UI.DomElement.removeCssClass($get('ChartDataContent'), 'loading');
$get('ChartDataContent').innerHTML = result;
$('#ChartDataContent').fadeIn(500);
}
function OnGetChartDataFailure(result) {
alert('Error loading control data');
}
Now at the point where the Ajax call to the service has succeeded I need to be able to get the chart to do its rendering etc to the container.
As it stands this is just using the example and there is no need for me to be using Ajax, but in practice there will be some long running calculations that need to take place before the chart is rendered.
If I need to add more information to this then please say and Ill do my best to explain further.
Thanks in advance
The simplest option you have is to use the Highcharts .Net library from codeplex that acts as a wrapper around the Highcharts js library, allowing you to create the charts using only C#.
However, if you so not want to go that way, you can always use a helper function to load the series into the chart as shown in the example here

Created function not found

I'm trying to create a simple function, but at runtime firebug says the function does not exist.
Here's the function code:
<script type="text/javascript">
function load_qtip(apply_qtip_to) {
$(apply_qtip_to).each(function(){
$(this).qtip(
{
content: {
// Set the text to an image HTML string with the correct src URL to the loading image you want to use
text: '<img class="throbber" src="/projects/qtip/images/throbber.gif" alt="Loading..." />',
url: $(this).attr('rel'), // Use the rel attribute of each element for the url to load
title: {
text: 'Nieuwsbladshop.be - ' + $(this).attr('tooltip'), // Give the tooltip a title using each elements text
//button: 'Sluiten' // Show a close link in the title
}
},
position: {
corner: {
target: 'bottomMiddle', // Position the tooltip above the link
tooltip: 'topMiddle'
},
adjust: {
screen: true // Keep the tooltip on-screen at all times
}
},
show: {
when: 'mouseover',
solo: true // Only show one tooltip at a time
},
hide: 'mouseout',
style: {
tip: true, // Apply a speech bubble tip to the tooltip at the designated tooltip corner
border: {
width: 0,
radius: 4
},
name: 'light', // Use the default light style
width: 250 // Set the tooltip width
}
})
}
}
</script>
And I'm trying to call it here:
<script type="text/javascript">
// Create the tooltips only on document load
$(document).ready(function()
{
load_qtip('#shopcarousel a[rel]');
// Use the each() method to gain access to each elements attributes
});
</script>
What am I doing wrong?
You are missing a ), closing the each call.
Change last line in the function declaration to
);}
For similar problems in the future, try pasting your code into http://www.jslint.com/

Categories

Resources