Tips for setting up Highcharts tooltip.headerFormat using the function getDate() plus 5

I'm facing a little challenge trying to understand how the JavaScript function getDate interacts with Highcharts datetime on xAxis.

My goal is to show two dates in the tooltip header, forming a date range like this: 1960/1/1 - 1965/1/1.

The first date is retrieved from point.key (a unix timestamp) in my dataset, which I have figured out how to set. However, displaying the second date as {5 years plus point.key} is where I need assistance.

Despite my limited understanding of JavaScript, I know that there is a function called getdate() which looks like this:

function getdate() {
    var tt = document.getElementById('txtDate').value;

    var date = new Date(tt);
    var newdate = new Date(date);

    newdate.setDate(newdate.getDate() + 3);

    var dd = newdate.getDate();
    var mm = newdate.getMonth() + 1;
    var y = newdate.getFullYear();

    var someFormattedDate = mm + '/' + dd + '/' + y;
    document.getElementById('follow_Date').value = someFormattedDate;
}

Is it possible for me to apply this function in generating the second date for my tooltip like so?

tooltip.headerFormat: '<span style="font-size: 16px">' +
                      '{point.key} - {point.key + 5 years}</span><br/>';

If you want to see the issue in action, check out this fiddle.

Answer №1

tooltip: {
    shared   : true,
    useHTML  : true,
    formatter: function() {
        var futureDate = new Date(this.x);
        futureDate.setFullYear(futureDate.getFullYear() + 5);
        var customTooltip = '<table><span style="font-size: 16px">'
                    + Highcharts.dateFormat('%e/%b/%Y', new Date(this.x)) + ' - '
                    + Highcharts.dateFormat('%e/%b/%Y', futureDate)
                    + '</span><br/><tbody>';
        //loop through each point in this.points
        $.each(this.points, function(i, point) {
            if (point.series.name === 'Observations') {

                customTooltip += '<tr><th style="font-size: 14px; color: ' + point.series.color
                        + '">' + point.series.name + ': </th>'
                        + '<td style="font-size: 14px">' + point.y + '℃' + '</td></tr>';

            } else if (point.series.name === 'BOXPLOT') {

                const x = this.x;
                const currentData = this.series.data.find(data => data.x === x);
                const boxplotValues = currentData ? currentData.options : {};
                customTooltip += `<span style="font-size: 14px; color: #aaeeee"> 
                        Max: ${boxplotValues.high.toFixed(2)}<br>
                            Q3: ${boxplotValues.q3.toFixed(2)}<br>
                            Median: ${boxplotValues.median.toFixed(2)}<br>
                            Q1: ${boxplotValues.q1.toFixed(2)}<br>
                            Low: ${boxplotValues.low.toFixed(2)}<br></span>`;

            } else {

                customTooltip += '<tr><th style="font-size: 14px; color: ' + point.series.color
                        +  '">' + point.series.name + ': </th><td style="font-size: 14px">'
                        +  point.point.low + '℃ -' + point.point.high + '℃' + '</td></tr>'
                        +  '</tbody></table>';

            }
      });
      return customTooltip;
    }
},

Answer №2

Is there a way to incorporate the function into my tooltip and display a second date in the tooltip headerFormat?

According to the specifications:

headerFormat: string
The HTML content of the tooltip header line. Variables are enclosed by curly brackets.[...]

It appears that the tooltip.headerFormat only accepts static strings. Any variables like {point.key} will be replaced using a search and replace mechanism. Unfortunately, you cannot use a function for tooltip.headerFormat.

If you need to use a formatter that can handle values dynamically through a callback function, you should utilize tooltip.formatter:

formatter: Highcharts.TooltipFormatterCallbackFunction
Callback function to format the text of the tooltip from scratch.[...]

When attempting to implement tooltip.formatter initially, it may seem like you have to restructure your tooltip code drastically. This could be due to inadequate preparation before commencing the coding. Exploring this further would be beyond the scope of this answer...


The "+5 years" Calculation:

var oDate = new Date( point.key );
return (5 + oDate.getFullYear()) + '/' + // add 5 years
       (1 + oDate.getMonth())    + '/' + // (January represents 0)
       oDate.getDate();

Note: The calculation above applies to regular years; not all years have 365 days. If you need to account for leap years in your calculation, consider utilizing a framework such as momentjs.com.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modifying the Vue.js Vue3-slider component for custom color schemes

Currently, I am using the vue-slider component and would like to customize the color of the slider itself. The specific class that needs to be styled is "vue-slider-dot-tooltip-inner". Below is a screenshot displaying the original CSS styling for vue-slid ...

Obtain a numerical output from a selection of numbers

I am facing a simple problem that I can't solve due to my lack of knowledge and have not been able to find any solution online. What I want to achieve is: Create a "value 1" from an array of integers. Generate a random "value 2". Check if the rando ...

Display the designated element upon clicking the designated link exclusively

I'm working with this specific HTML setup: <a href="#" class="dp">Click me</a> <div class="dp_div" style="display: none;"> this is the content within the div </div> My goal is to display the hidden div with a class of "dp_ ...

Can you explain the significance of the error message stating "XMLHttpRequest.timeout cannot be set for synchronous http(s) requests made from the window context"?

I'm experiencing some timeouts with a synchronous XML HTTP request in Safari on my Mac. In an attempt to fix this issue, I added a timeout setting like this: req.open(this.method, fullURL, this.isAsync); req.setRequestHeader('Content-Typ ...

Navigate to the end of the progress bar once finished

I have a solution that works, but it's not very aesthetically pleasing. Here is the idea: Display a progress bar before making an ajax call Move the progress bar to the end once the call is complete (or fails) Keep the progress bar at 90% if the aj ...

Verify whether the value is considered false, true, or null

When dealing with variables in JavaScript, I often need to determine if a variable is false, true, or null. If the variable is null or undefined, I want to assign an array to it by default. While this syntax works well in other languages, in JS assigning a ...

Utilizing Polymer 3 in a different context such as ASP.NET MVC allows for the development of versatile components known as PolymerElements that can be reused

I am currently working on integrating Polymer 3 components into my ASP.NET MVC application. I'm not entirely sure if my approach to this issue is correct at the moment. My main goal is to execute everything from IIS Express. However, I'm encou ...

Tips on incorporating CKEditor4 wiris MathML formulas into react JS

I am having trouble displaying MathML in the DOM. When I try to render it, the output is not showing correctly in the Editor. I am utilizing CKEditor4 Let me share the code below to provide more context on what I have attempted so far App.js file: impo ...

How can I pass command line variables into an npm script?

I am facing an issue where I am attempting to pass a command line option (which is not stored in version control) to my main script index.js. This script performs specific actions based on a designated S3 bucket. Here is the relevant section from my packa ...

Converting PHP arrays into JavaScript arrays with the help of json_encode()

Is there a way to pass an array from PHP to the JavaScript function console.log()? I'm currently simulating a database and need help with this specific task. Despite not having an array declared in my code, I attempted to use the .getJSON() function w ...

JavaScript debugging causing system freeze

Currently, I am working on a project that involves using MVC and dropdown lists. My issue arises when the dropdown list changes, as there is some javascript code that needs to execute. To troubleshoot the problem of the system locking up every time I tried ...

What is the best way to integrate custom JavaScript files into a Vue project?

I recently downloaded an HTML template from a website and now I am looking to convert the entire template into a Vue CLI project. The template includes jQuery and other custom JavaScript files. While I was able to use npm packages for jQuery and Bootstrap, ...

Divs in jQuery smoothly slide down when a category is chosen

As I work on a large website, I have hidden div tags in my HTML that I want to be displayed when a user selects a specific category. However, due to the size of the site, there are many hidden divs that need to be revealed based on different categories sel ...

Error Alert: Invalid Hook Call detected while using the useSelector hook within a Functional Component

I am encountering an error Error: Invalid hook call. Hooks can only be called inside of the body of a function component. The versions of React and the renderer (such as React DOM) might not match There could be violations of the Rules of Hooks Multiple ...

What is the purpose of passing functions down to components in React?

It's interesting to think about why we choose to define all component functions in one central location, such as index.js, and then pass them down. Is there a good reason for this approach? For instance, if I need to create a click handler for a list ...

Utilizing React JS to dynamically populate a table with data from an external JSON file

As a newcomer to the realm of React, I am facing challenges in displaying my JSON data in a table. class GetUnassignedUsers extends React.Component { constructor () { super(); this.state = { data:[] }; } com ...

Maintaining current object relationships in the React state

I'm currently grappling with the challenge of creating a JSON model for managing state in a React component. Previously, I relied on Entity Framework and virtual properties to establish relationships between "tables." However, transitioning to React a ...

Encountering an issue while setting up the ContextAPI in nextJS, where properties of undefined Provider cannot be read

I'm encountering difficulties in implementing ContextAPI with a nextjs application. The error message I keep receiving is: TypeError: Cannot read properties of undefined (reading 'Provider') This is my approach to creating the context: impo ...

Can an entire object be bound to a model in an Angular controller function?

In TypeScript, I have defined the following Interface: interface Person { Id: number; FirstName: string; LastName: string; Age: number; } Within a .html partial file, there is an Angular directive ng-submit="submit()" on a form element. A ...

Why does TypeScript keep throwing the "No inputs were found in the config file" error at me?

Why am I receiving the No inputs were found in config file error from TypeScript? I have set up my tsconfig.json in VS Code, but the error occurs when I try to build it. The terminal displays: error TS18003: No inputs were found in config file '/Use ...