Highstock panning asynchronously loading data - javascript

Using Highstock is it possible to drag the chart and load the data asynchronously?
I've seen the async demo on the highcharts website http://jsfiddle.net/hcharge/5zPLV/
However this uses the navigator/scrollbar to move the chart along the series and loads the data when you stop sliding it along, Ideally I want to use the panning capability of highstock to move along instead of the navigator as it takes up too much space.
Playing around with the demo if I turn off the navigator and scrollbar and disable the zoomtype: x then as soon as you start dragging the chart it tries to fetch the data, making the chart unusable. Here is a fiddle of that http://jsfiddle.net/hcharge/6YSvk/
navigator: {enabled: false}, scrollbar: {enabled: false}
Ideally we'd need to know when the user starts dragging and when they stop then load the data.
Is this even possible to do? Thanks

I think this is possible, but it won't be easy.
As you wrote, you should start with detecting drag & drop. It's not possible using build-in options, but we can add our own event listeners. Take a look at this code:
new Highcharts.StockChart({
// here comes your chart options, but we can pass callback function as the second parameter
}, function (chart) {
var report = document.getElementById('report'), // just an element to display current extremes
xAxis = chart.xAxis[0],
startX;
function drag(e) {
e = chart.tracker.normalizeMouseEvent(e);
startX = e.chartX;
}
function drop(e) {
e = chart.tracker.normalizeMouseEvent(e);
var delta = e.chartX - startX,
extremes = xAxis.getExtremes(),
newMin = Math.round(extremes.min - delta),
newMax = Math.round(extremes.max - delta);
// display extremes retrieved by panning
report.innerHTML = "<b>From:</b> " + new Date(newMin) + " <b>to:</b> " + new Date(newMax);
}
// bind events
Highcharts.addEvent(chart.container, 'mousedown', drag);
Highcharts.addEvent(chart.container, 'mouseup', drop);
});
Simply we detect mouseDown & mouseUp events, then calculate the difference, translate difference to x data and finally, substract difference from extremes.
Here you can find the jsfiddle demo with code posted above: http://jsfiddle.net/dSEAA/1/

To make #slawekkolodziej's example work, you need to translate the delta into ms on the xAxis, then update the xAxis extremes like so:
window.chart = new Highcharts.StockChart({
// chart options go here
}, function(chart) {
var xAxis = chart.xAxis[0],
startX;
function drag(e) {
e = chart.pointer.normalize(e);
startX = e.chartX;
}
function drop(e) {
e = chart.pointer.normalize(e);
var delta = e.chartX - startX,
extremes = xAxis.getExtremes(),
deltaMs = (extremes.max - extremes.min) / chart.plotWidth * delta,
newMin = Math.round(extremes.min - deltaMs),
newMax = Math.round(extremes.max - deltaMs);
xAxis.setExtremes(newMin, newMax)
}
Highcharts.addEvent(chart.container, 'mousedown', drag);
Highcharts.addEvent(chart.container, 'mouseup', drop);
});
});
Here's a working example with async data loading: http://jsfiddle.net/xw7goLj4/5/

Related

RxJS: distinguish single click from drag

I have an AngularJS component that should react to either a single click or a drag (resizing an area).
I started to use RxJS (ReactiveX) in my application, so I try to find a solution using it. The Angular side of the request is minor...
To simplify the problem (and to train myself), I made a slider directive, based on the rx.angular.js drag'n'drop example: http://plnkr.co/edit/UqdyB2
See the Slide.js file (the other code is for other experiments). The code of this logic is:
function(scope, element, attributes)
{
var thumb = element.children(0);
var sliderPosition = element[0].getBoundingClientRect().left;
var sliderWidth = element[0].getBoundingClientRect().width;
var thumbPosition = thumb[0].getBoundingClientRect().left;
var thumbWidth = thumb[0].getBoundingClientRect().width;
// Based on drag'n'drop example of rx-angular.js
// Get the three major events
var mousedown = rx.Observable.fromEvent(thumb, 'mousedown');
var mousemove = rx.Observable.fromEvent(element, 'mousemove');
var mouseup = rx.Observable.fromEvent($document, 'mouseup');
// I would like to be able to detect a single click vs. click and drag.
// I would say if we get mouseup shortly after mousedown, it is a single click;
// mousedown.delay(200).takeUntil(mouseup)
// .subscribe(function() { console.log('Simple click'); }, undefined, function() { console.log('Simple click completed'); });
var locatedMouseDown = mousedown.map(function (event)
{
event.preventDefault();
// console.log('Click', event.clientX - sliderPosition);
// calculate offsets when mouse down
var initialThumbPosition = thumb[0].getBoundingClientRect().left - sliderPosition;
return { from: initialThumbPosition, offset: event.clientX - sliderPosition };
});
// Combine mouse down with mouse move until mouse up
var mousedrag = locatedMouseDown.flatMap(function (clickInfo)
{
return mousemove.map(function (event)
{
var move = event.clientX - sliderPosition - clickInfo.offset;
// console.log('Move', clickInfo);
// calculate offsets from mouse down to mouse moves
return clickInfo.from + move;
}).takeUntil(mouseup);
});
mousedrag
.map(function (position)
{
if (position < 0)
return 0;
if (position > sliderWidth - thumbWidth)
return sliderWidth - thumbWidth;
return position;
})
.subscribe(function (position)
{
// console.log('Drag', position);
// Update position
thumb.css({ left: position + 'px' });
});
}
That's mostly D'n'D constrained horizontally and to a given range.
Now, I would like to listen to mousedown, and if mouse up happens within a short while (say 200 ms, to adjust), I see it as a click and I do a specific treatment (eg. resetting the position to zero).
I tried with delay().takeUntil(mouseup), as seen in another SO answer, without success. Perhaps a switch() might be needed, too (to avoid going the drag route).
Any idea? Thanks in advance.
You can use timeout (timeoutWith if you are using ReactiveX/RxJS)
var click$ = mousedown.flatMap(function (md) {
return mouseup.timeoutWith(200, Observable.empty());
});
If the mouseup doesn't occur before the timeout it will just propagate an empty Observable instead. If it does then the downstream observer will receive an event.
Isn't the trick with delay(Xms).takeUntil(mouseup) doing the opposite of what you want? I mean, you want to detect when the mouseup event happens before the countdown, while the aformentioned trick detect when the mouseup event happens after.
I would try something around those lines (untested for now, but hopefully it will orient you in some positive direction):
var click$ = mousedown.flatMap(function ( mouseDownEv ) {
return merge(
Rx.just(mouseDownEv).delay(Xms).map(function ( x ) {return {event : 'noclick'};}),
mouseup.map(function ( mouseUpEv ) {return {event : mouseUpEv};})
).first();
});
The idea is to race the mouseup event against a dummy emission happening after your delay, and see who wins. So if click$ emits 'noclick' then you can consider that no click happened.
Hopefully that works, i will test soon but if you do before me, let me know.

Flot event for range updates in response to panning/zooming

For Flot, is there an event that fires after the user has completed panning or zooming using the mouse scroll wheel (after the range.xaxis.to/from and range.yaxis.to/from have settled)? I am trying to use the line below to update the selection on an overview plot after the user has panned or zoomed in the main plot, but am finding that either the update to the overview plot happens after panning or zooming(not both).
$("#plot").bind("mouseup scroll",updateOverviewSelection);
Edit: http://jsfiddle.net/apandit/nu2rr58h/9/
In the jsfiddle, I am unable to pan in the main plot and the cursor does not seem to change back to normal. The user can click and drag in the overview plot to make a selection, which leads to zooming in the main plot. I would also like to be able to allow the user to pan and zoom in the main plot and have the selection box in the overview plot updated; I am attempting to do this by binding the updateOverviewSelection method to the plot div for the scroll and mouseup events. Is there an event in Flot that fires every time the x- and y-axis limits are updated?
The solution to this issue is below. The issue was that setting the overview plot's selection(overview.setSelection(ranges);) was triggering the zoom method because it was bound to the plotselected event in the overview plot. At the end of the zoom method, the main plot was plotted, which was again calling the overview.setSelection(ranges); line in the updateOverviewSelection method. To prevent this ping-pong between the two methods/events, I added an updatingOverviewSelection flag.
http://jsfiddle.net/apandit/nu2rr58h/12/
var datasets = [[
[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9]
],
[
[0,0],[-1,-1],[-2,-2],[-3,-3],[-4,-4],[-5,-5],[-6,-6],[-7,-7],[-8,-8],[-9,-9]
]];
var plot = $.plot("#plot",datasets,{
pan: {
interactive: true
},
zoom: {
interactive: true,
mode: "x"
}
});
var overview = $.plot("#overview",datasets,{
selection: {
mode: "xy"
}
});
var updatingOverviewSelection = false;
$("#plot").bind("plotpan plotzoom",updateOverviewSelection);
$("#overview").bind("plotselected", zoom);
function zoom(event,ranges) {
if(updatingOverviewSelection) {
updatingOverviewSelection = false;
}
else {
var options = plot.getOptions();
options.xaxes[0].min = ranges.xaxis.from;
options.xaxes[0].max = ranges.xaxis.to;
options.yaxes[0].min = ranges.yaxis.from;
options.yaxes[0].max = ranges.yaxis.to;
plot = $.plot("#plot",datasets,options);
}
};
// get the window x-axis and y-axis ranges for the main plot
// and set the selection in the overview plot to those ranges
function updateOverviewSelection(event) {
var options = plot.getOptions();
var ranges = {
xaxis: {
from: options.xaxes[0].min,
to: options.xaxes[0].max
},
yaxis: {
from: options.yaxes[0].min,
to: options.yaxes[0].max
}
};
updatingOverviewSelection = true;
overview.setSelection(ranges);
};

Bar Chart outside bounds and mouseover event issue

Here is my dimple.js code, the bar chart that it produces is outside the bounds and touching Y-axis.
Mouseover event is not changing the color of the bars.
Below is the image
var myChart2 = new dimple.chart(svg,data);
myChart2.setBounds(750,50,550,250);
var x = myChart2.addTimeAxis( "x", "date", "%m/%d/%Y", "%d-%b");
x.floatingBarWidth = 21;
var y2= myChart2.addMeasureAxis("y","callperorder");
var y1= myChart2.addMeasureAxis("y","calls");
var bars = myChart2.addSeries("or", dimple.plot.bar,[x,y2]);
var lines= myChart2.addSeries("cl", dimple.plot.line,[x,y1]);
lines.lineMarkers= true;
myChart2.addLegend(750, 20, 300, 20, "right");
myChart2.assignColor("cl","rgb(99,39,29)");
myChart2.assignColor("or","rgb(99,89,219)");
myChart2.draw();
\\MOUSEOVER EVENT
bars.addEventHandler("mouseover", function( {d3.select(this).style("fill","green")});
You need to add the event handler before calling draw if you want to use the dimple method. Alternatively you could use the d3 method after draw.
bars.shapes.on("mouseover", function () {...});
NB. There's also a typo in your event declaration, it's missing the closing bracket after function (.
In order to avoid overlapping the edge of the chart you will need to manually set the x bounds:
x.overrideMin = d3.time.format("%m/%d/%Y").parse("12/31/2014");
x.overrideMax = d3.time.format("%m/%d/%Y").parse("01/11/2015");
Using whatever values you want of course;

jsPlumb and jQuery.PanZoom dragging issue

I used jquery.panzoom plugin in order to zoom and pan jsPlumb diagrams and every things is working find but when i zoom and drag an element this one goes far away from the pointer!
Does someone facing the same issue? can some one help me with this?
Thanks
see this
http://jsfiddle.net/a4v2guvt/
$panzoom.on('panzoomzoom', function (e, panzoom, scale) {
jsPlumb.setZoom(scale);
});
To fix this i used jQueryUI/draggable instead of builtin one:
var currentScale = 1;
$container.find(".diagram .item").draggable({
start: function(e){
var pz = $container.find(".panzoom");
//we need current scale factor to adjust coordinates of dragging element
currentScale = pz.panzoom("getMatrix")[0];
$(this).css("cursor","move");
pz.panzoom("disable");//disable panzoom to avoid double offset
},
drag:function(e,ui){
//fix scale issue
ui.position.left = ui.position.left/currentScale;
ui.position.top = ui.position.top/currentScale;
if($(this).hasClass("jsplumb-connected"))
{
plumb.repaint($(this).attr('id'),ui.position);
}
},
stop: function(e,ui){
var nodeId = $(this).attr('id');
plumb.repaint(nodeId,ui.position);
$(this).css("cursor","");
//enable panzoom back
$container.find(".panzoom").panzoom("enable");
}
});
Look at this demo

mouseOver in Highcharts

I have a chart. There is no mouseOver event in chart options, but I need to get mouse coordinates when I move cursor. For example, I want to show coordinates on xAxis and yAxis. Is it possible?
You can catch mousevent on the div which contain highcharts.
http://jsfiddle.net/5KHaj/2/
$('#highcharts-0').mouseover(function(e){
$('#report').html(e.clientX + ' ' + e.clientY);
});
Get the normal mouse coordinates then calculate the relative position.
document.body.onmousemove = function (event) {
var x = event.target.x - <your_chart_element>.getBoundingClientRect().left
var y = event.target.y - <your_chart_element>.getBoundingClientRect().top
}

Categories