Created function not found - javascript

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/

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".

How do I encode HTML characters within Javascript functions?

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.

Jsplump dynamically draw state machine diagram

I am using jsplumb to draw dynamic state machine diagram. On click of a button I need to add new box in a drawing area and allow user to position it as per their need.
I am not getting any proper easy to understand documentation for this. I tried few things:
var i=8;
function AddDiv() {
var obj = new Date();
var Div = $('<div/>', {
'class':'box ui-draggable ui-draggable-handle ui-droppable',
'id':'box_'+i,
'html':'BOXESNEW'
}).appendTo('.statemachine_cont');
jsPlumb.addEndpoint($(Div), targetEndpoint);
$(Div).draggable(
{
drag: function(){
jsPlumb.repaint($(this)); // (or) jsPlumb.repaintEverything(); to repaint the connections and endpoints
// jsPlumb.addEndpoint($(this));
}
});
$(Div).addClass('box ui-draggable ui-draggable-handle ui-droppable');
}
var a = $("#a");
//Setting up drop options
var targetDropOptions = {
activeClass: 'dragActive'
};
//Setting up a Target endPoint
var targetColor = "#BEBEBE";
var targetEndpoint = {
anchor: "BottomCenter", //Placement of Dot
endpoint: ["Dot", { radius: 8}], //Other types are rectangle, Image, Blank, Triangle
paintStyle: { fillStyle: targetColor }, //Line color
isSource: true, //Starting point of the connector
// scope: "green dot",
connectorStyle: { strokeStyle: "#5C96BC", lineWidth: 2 }, // Means Bridge width and bridge color
connector: ["Bezier"], //Other properties Bezier
maxConnections: -1, //No upper limit
isTarget: true, //Means same color is allowed to accept the connection
dropOptions: targetDropOptions //Means when the drag is started, other terminals will start to highlight
};
jsPlumb.bind("ready", function () {
//Set up endpoints on the divs
jsPlumb.addEndpoint($(".box ui-draggable ui-draggable-handle ui-droppable"), targetEndpoint);
jsPlumb.addEndpoint($(".box ui-draggable ui-draggable-handle ui-droppable"), sourceEndpoint);
jsPlumb.draggable($(".box ui-draggable ui-draggable-handle ui-droppable"));
jsPlumb.animate($("#a"), { "left": 50, "top": 100 }, { duration: "slow" });
});
Not sure what I have done is correct, I referred to some online code available and modified it.
My issue here is: Onclick of a button I am able to add a new box and also able to drag a connection from that box. But when I try to drag that box (i.e change its position), the connection does not move. Box is moved but I am unable to move the connection with the box.
When I try to move the newly added box or the box connected to new one, both the boxes can be moved but the connection remains static and doesn't move. where as if other boxes are moved it moves along with the connections. I have added a image of that for reference.
1st image shows how newly added box and new connection appears. 2nd image shows how moving of the box creates the issue.
Here is how I manged to get it working. I modified my entire code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='js/jquery-1.10.1.js'></script>
<link rel="stylesheet" type="text/css" href="css/demo-all.css">
<link rel="stylesheet" type="text/css" href="css/demo.css">
<script type='text/javascript' src="js/jquery.ui.touch-punch-0.2.2.min.js"></script>
<script type='text/javascript' src="js/jquery-ui-1.9.2.min.js"></script>
<script type='text/javascript' src="js/jquery.jsPlumb-1.7.2-min.js"></script>
<style type='text/css'>
.hidden { display: none; }
</style>
<script type='text/javascript'>
$(window).load(function(){
function cloneWindow(instance) {
var $jspContainer = $("#statemachine-demo"),
divid = "fromTemplate_" + new Date().getTime().toString()
$cloneElement = $("<div class='w'>New Window <div class='ep'></div></div>").attr("id", divid);
$jspContainer.append($cloneElement);
instance.draggable(divid);
instance.makeSource($cloneElement, {
filter: ".ep", // only supported by jquery
anchor: "Continuous",
connector: ["StateMachine", {
curviness: 1
}],
connectorStyle: {
strokeStyle: "#5c96bc",
lineWidth: 2,
outlineColor: "transparent",
outlineWidth: 4
},
maxConnections: 10,
onMaxConnections: function (info, e) {
alert("Maximum connections (" + info.maxConnections + ") reached");
}
});
instance.bind("connection", function (info) {
info.connection.getOverlay("label").setLabel(info.connection.id);
});
instance.makeTarget($cloneElement, {
anchor:"Continuous",
dropOptions:{ hoverClass:"dragHover" }
});
}
jsPlumb.ready(function () {
$("#addwindow").click(function() {
cloneWindow(instance);
});
// setup some defaults for jsPlumb.
var instance = jsPlumb.getInstance({
Endpoint: ["Dot", {
radius: 2
}],
HoverPaintStyle: {
strokeStyle: "#1e8151",
lineWidth: 2
},
ConnectionOverlays: [
["Arrow", {
location: 1,
id: "arrow",
length: 14,
foldback: 0.8
}],
["Label", {
label: "Drag this and drop it on another element to make a connection.",
id: "label",
cssClass: "aLabel"
}]
],
Container: "statemachine-demo"
});
jsPlumb.importDefaults({
filter: ".ep",
anchor: "Continuous",
connector: ["StateMachine", {
curviness: 1
}],
connectorStyle: {
strokeStyle: "#5c96bc",
lineWidth: 2,
outlineColor: "transparent",
outlineWidth: 4
},
maxConnections: 10,
dropOptions: {
hoverClass: "dragHover"
}
});
var windows = jsPlumb.getSelector(".statemachine-demo .w");
// initialise draggable elements.
instance.draggable(windows);
// bind a click listener to each connection; the connection is deleted. you could of course
// just do this: jsPlumb.bind("click", jsPlumb.detach), but I wanted to make it clear what was
// happening.
instance.bind("click", function (c) {
instance.detach(c);
});
// bind a connection listener. note that the parameter passed to this function contains more than
// just the new connection - see the documentation for a full list of what is included in 'info'.
// this listener sets the connection's internal
// id as the label overlay's text.
instance.bind("connection", function (info) {
info.connection.getOverlay("label").setLabel(info.connection.id);
});
// suspend drawing and initialise.
instance.doWhileSuspended(function () {
// make each ".ep" div a source and give it some parameters to work with. here we tell it
// to use a Continuous anchor and the StateMachine connectors, and also we give it the
// connector's paint style. note that in this demo the strokeStyle is dynamically generated,
// which prevents us from just setting a jsPlumb.Defaults.PaintStyle. but that is what i
// would recommend you do. Note also here that we use the 'filter' option to tell jsPlumb
// which parts of the element should actually respond to a drag start.
instance.makeSource(windows, {
filter: ".ep", // only supported by jquery
anchor: "Continuous",
connector: ["StateMachine", {
curviness: 1
}],
connectorStyle: {
strokeStyle: "#5c96bc",
lineWidth: 2,
outlineColor: "transparent",
outlineWidth: 4
},
maxConnections: 10,
onMaxConnections: function (info, e) {
alert("Maximum connections (" + info.maxConnections + ") reached");
}
});
// initialise all '.w' elements as connection targets.
instance.makeTarget(windows, {
dropOptions: {
hoverClass: "dragHover"
},
anchor: "Continuous"
});
// and finally, make a couple of connections
instance.connect({
source: "opened",
target: "phone1"
});
instance.connect({
source: "phone1",
target: "inperson"
});
instance.connect({
source: "phone1",
target: "phone1"
});
});
});
});
</script>
</head>
<body>
<div class="demo statemachine-demo" id="statemachine-demo" style="border:2px solid;border-radius:25px;">
<button type="button" id="addwindow">Add Window</button>
<div class="w" id="opened">BEGIN
<div class="ep"></div>
</div>
<div class="w" id="phone1">PHONE INTERVIEW 1
<div class="ep"></div>
</div>
<div class="w" id="phone2">PHONE INTERVIEW 2
<div class="ep"></div>
</div>
<div class="w" id="inperson">IN PERSON
<div class="ep"></div>
</div>
<div class="w" id="rejected">REJECTED
<div class="ep"></div>
</div>
<div class="w hidden" id="template_newwindow">
<div class="ep"></div>
</div>
</div>
</body>
</html>
Div is already a jquery object, there is no need to wrap it again.
Option 1
Div.draggable(
{
drag: function(){
jsPlumb.repaintEverything();
}
});
Option 2
jsPlumb.draggable(Div.attr('id'));

Bootstrap + Zeroclipboard = Tooltips can't be shown on hover?

I'm trying to use ZeroClipboard for a "Click to copy" feature on an element and the same time show a bootstrap tooltip.
Unfortunately the tooltip doesn't work if I use ZeroClipboard on an element. Any help would be greatly appreciated...
// BOOTSTRAP TOOLTIP
$('.myDiv').tooltip({
title: 'Click to copy',
placement: 'right',
trigger: 'hover',
animation: true
});
// ZEROCLIPBOARD
var clip = new ZeroClipboard.Client();
clip.setHandCursor(true);
$('.myDiv').live('mouseover', function () {
clip.setText($(this).text());
if (clip.div) {
clip.receiveEvent('mouseout', null);
clip.reposition(this);
} else clip.glue(this);
clip.receiveEvent('mouseover', null);
});
Managed to get it working in a very simple way
var zero = new ZeroClipboard($el);
$(zero.htmlBridge).tooltip({title: "copy to clipboard", placement: 'bottom'});
Sometimes it is hard to get all the snippets together and to work ... this is a complete solution using ZeroClipboard 1.3.2 and Bootstrap 3.1.0:
HTML:
<a id="copycommand" href="#" data-clipboard-text="text to copy">Copy ...</a>
ZeroClipboard create a container with the ID global-zeroclipboard-html-bridge, this is the access point for the Bootstrap Tooltip.
jQuery:
// initialize Tooltip
$('#global-zeroclipboard-html-bridge').tooltip();
// ZeroClipboad
ZeroClipboard.config({ moviePath: 'ZeroClipboard.swf' });
var clip = new ZeroClipboard(document.getElementById('copycommand'));
clip.on('complete', function(client, args){
alert("Copied text to clipboard: " + args.text);
});
// settings for the Tooltip
clip.on('load', function(client) {
$('#global-zeroclipboard-html-bridge').attr({
'data-toggle':'tooltip',
'data-title': 'Tooltip text goes here ...',
'data-placement': 'bottom',
'data-html': true
});
// show the tooltip
$('#global-zeroclipboard-html-bridge').tooltip('show');
});
If you run Tooltip after ZeroClipboard it should work without problems!
Found a workaround by putting the tooltip to be shown on click for Bootstrap, but then using hooks in ZeroClipboard to show and hide it upon hover.
Here is how I did it:
$('div.color-inspiration span').tooltip({
title: 'Click to copy',
placement: 'right',
trigger: 'click',
animation: false
});
var element = null;
var clip = new ZeroClipboard.Client();
clip.setHandCursor(true);
$('div.color-inspiration span').live('mouseover', function () {
element = $(this);
clip.setText($(this).text());
if (clip.div) {
clip.receiveEvent('mouseout', null);
clip.reposition(this);
} else clip.glue(this);
clip.receiveEvent('mouseover', null);
});
clip.addEventListener( 'onMouseOver', my_mouse_over_handler );
function my_mouse_over_handler( client ) {
$(element).tooltip('show');
}
clip.addEventListener( 'onMouseOut', my_mouse_out_handler );
function my_mouse_out_handler( client ) {
$(element).tooltip('hide');
}
clip.addEventListener( 'onMouseUp', my_mouse_up_handler );
function my_mouse_up_handler( client ) {
$(element).tooltip('hide');
}
Old question but I recently encountered this problem and was able to find a solution, it's rather simple but a bit blanket. Because the flash element positions itself with a zindex of 10000 on top of whatever element you have on the page you'll have to append the flash element with a selector and title. This can be done with the ZeroClipboard callbacks.
clip.on( 'load', function(client) {
$('#global-zeroclipboard-html-bridge').attr('rel', 'tooltip').attr('title', 'Click Here To Copy URL');
} );
With Zero Clipboard 2.2 and Bootstrap 3 I got it to work like this
var $copyButton = $('.clipboard');
var clip = new ZeroClipboard($copyButton);
clip
.on('ready', function() {
$('#global-zeroclipboard-html-bridge').attr({
'data-toggle': 'tooltip',
'data-title': 'Copy to clipboard...',
'data-placement': 'right'
});
$('#global-zeroclipboard-html-bridge').tooltip({
container: 'body',
trigger: 'hover'
});
})
.on('aftercopy', function() {
$('#global-zeroclipboard-html-bridge').tooltip('hide');
});
Change the selector on line one.
the #global-zeroclipboard-html-bridge selector targets a div that is inserted by the Zero Clipboard component and that overlays the copy button.
bug is a known issue and mentioned here: Zeroclipboard bug causing issue: see # https://github.com/zeroclipboard/zeroclipboard/issues/369
Adding to #gnorsilva's answer. Here is how I set new text on the tooltip once it was copied successfully:
$(clip.htmlBridge).tooltip({
title: 'copy to clipboard',
placement: 'bottom'
});
clip.on('load', function(client) {
client.on('complete', function() {
$('.tooltip .tooltip-inner').text('copied!');
});
});
This achieves the same effect as GitHub when you click one of their ZeroClipboard elements such as copy SHA or when you click the clone URL button

Highcharts: Add a custom image button

I want to add and image button on highcharts.
So far, I have successfully created a image button and have attached a click event on it.
But problem is that, the image (sun.png) is on left side of chart and image button is right aligned ( the default position of toolbar). Any fix for this ?
exporting: {
buttons: {
popUpBtn: {
symbol: 'url(images/sun.png)',
_titleKey: 'popUpBtnTitle',
x: -10,
symbolFill: '#B5C9DF',
hoverSymbolFill: '#779ABF',
onclick: function () {
alert('ad');
popUpChart($(this));
}
},
exportButton: {
enabled: false
},
printButton: {
enabled: false
}
}
}
Also, if there are other methods to add an image in chart which have click event, those methods are welcomed too.
Finally, I figured it out like this.
May be it will help others.
function callback($this){
var img = $this.renderer.image('images/zoom_icon.png',$this.chartWidth-40,5,40,12);
img.add();
img.css({'cursor':'pointer'});
img.attr({'title':'Pop out chart'});
img.on('click',function(){
// prcessing after image is clicked
});
}
new Highcharts.Chart(charts.params,callback);
// where charts.params is object which contains options for chart

Categories

Resources