Tracking without long-press
Crosshair
Crosshair tracking on touch devices without a long press.
Interactive example — scroll, zoom, and hover the chart.
Code
// Lightweight Charts™ Example: Tracking without long-press
// https://tradingview.github.io/lightweight-charts/examples/crosshair/tracking-without-long-press
document.getElementById('container').addEventListener('touchmove', e => {
const bcr = document.getElementById('container').getBoundingClientRect();
// Touch coordinates are relative to the viewport; the chart's are relative to the container.
const x = e.touches[0].clientX - bcr.left;
const y = e.touches[0].clientY - bcr.top;
const price = mainSeries.coordinateToPrice(y);
const time = chart.timeScale().coordinateToTime(x);
if (!Number.isFinite(price) || !Number.isFinite(time)) {
return;
}
chart.setCrosshairPosition(price, time, mainSeries);
});
document.getElementById('container').addEventListener('touchend', () => {
chart.clearCrosshairPosition();
});
The code expects the library’s exports, such as createChart, to be imported and a div with the id container on the page. Copy as HTML gives a page that runs on its own.
How it works
On touch screens the crosshair appears after a long press, because a plain swipe scrolls the chart. With scrolling and scaling turned off, the crosshair can follow the finger right away.
handleScroll: falseandhandleScale: falsein the chart options free touch moves from scrolling.- A
touchmovelistener on the container converts the touch position to a price withcoordinateToPriceand to a time withcoordinateToTime. setCrosshairPositionmoves the crosshair there. Atouchendlistener clears it withclearCrosshairPosition.
Open the page on a phone, or in a browser's device mode, to try it.
Resources
setCrosshairPositionHandleScrollOptions- Related examples: Sync two charts