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

partial download between servers

I have been attempting to transfer/copy a large file from a remote server to my server in segmented parts or chunks. My initial approach involved utilizing a script I found here: . After making some modifications, I integrated a form into the script and e ...

Determine if the given text matches the name of the individual associated with a specific identification number

Struggling to create a validation system for two sets of fields. There are 6 inputs in total, with 3 designated for entering a name and the other 3 for an ID number. The validation rule is that if an input with name="RE_SignedByID" contains a value, then c ...

The functionality to deselect multiple options in a select box is not functioning properly

There seems to be an issue with removing the selected attribute from the selected values in a jQuery multiselect box. The console is not showing any errors. You can view a working example here The problem lies in this code snippet: $("#mltyslct option ...

Angular 2: Encounter with 504 Error (Gateway Timeout)

I am struggling with handling errors in my Angular 2 application. Whenever the backend server is offline, an uncaught error appears in the console: GET http://localhost:4200/api/public/index.php/data 504 (Gateway Timeout) This is how my http.get me ...

Place the dataLabel above a specified column in Highcharts

My bar chart has a stacked design, with an invisible bar added to the height of the tallest bar to ensure clickability even for small values. Without this invisible stack, columns with a value of 1 would be difficult to click on. One issue I am facing is ...

Is there a way to verify the presence of a particular value in a list?

I need to validate the content of all li tags within a ul list. If any list item contains the text "None," then I want to append specific text to a div. If no li tag includes "None," then different text should be added to the div. Upon checking my code, I ...

What could be causing my JavaScript alert to not appear on the screen?

Essentially, I've been attempting to trigger a Javascript alert using PHP. However, the alert isn't functioning at all. This is my echo statement that dynamically generates the alert echo "<script>alert('Uploaded file was not in the ...

Is it possible for numerous identical components to trigger the display of the identical modal on a single webpage?

I am currently utilizing Vue in my project and I have a component that displays a button. When this button is clicked, it triggers a modal to open which is also part of the same component. The functionality works as intended. However, if there are multipl ...

Elevation in design ui component

I am having an issue with the height of a theme-ui component I embedded. Even though the console shows it correctly, it is displaying at 100% height. <Embed src={url} sx={{width: '800px', height: '400px'}}/> This embed is contain ...

Tips for correctly implementing CORS (Cross-Origin Resource Sharing)

Is there a way to securely access a resource from a third-party domain using XML HTTP Requests (XHR, AJAX)? I have set up CORS on both the target and origin sides with the following configuration: Access-Control-Allow-Origin: http://www.example.com, http ...

When the caret triangle is upside down, it indicates that a drop-down menu is available even when the

I am facing an issue with a dropdown list where the triangle indicator is incorrectly displayed: https://i.stack.imgur.com/L4NBW.png Both images show that the arrows are in reverse direction, and I am struggling to identify the cause of this problem. He ...

The styling of a CSS class in Internet Explorer may not be applied correctly if there are multiple elements sharing the same class name

For nearly a full week now, I've been plagued by a persistent issue! Here's the situation: I have 6 step tabs - step 1, step 2, and so on. Each tab has a CSS class called "locked" and "active." "Locked" - this style features top: 3em;, causing ...

Stop ngOnChanges from being triggered after dispatching event (Angular 2+)

In Angular 2+, a custom two-way binding technique can be achieved by utilizing @Input and @Output parameters. For instance, if there is a need for a child component to communicate with an external plugin, the following approach can be taken: export class ...

What is the most efficient way to add an attribute in jQuery - using the attr() method, passing attributes as a key-value object, or directly?

There are three ways that I am aware of for adding a href attribute with a relative link in jQuery: using (1) .attr(), (2) attributes as key-value pair in an argument, or (3) direct writing (if you know other methods, please share in your response so I can ...

Converting dynamic content within a div into an interactive link

I am currently working with Longtail's JW Player and facing some difficulties with a basic function. Since I am not familiar with the programming language terminologies, I will describe the issue step by step: There is a JavaScript code that displays ...

Center column with header and footer flanking each side

Trying to replicate the layout of the Facebook Android app on my page. The app features a 3 column design, with the central column exclusively displaying the header (no footer included, although I require one for my version). This visual representation is ...

Reset input fields while retaining placeholder text

Seeking advice on how to use this handy jQuery tool properly: $('.myDiv input').each(function () { $(this).val(""); }); Though it clears my form, I'm struggling to maintain the placeholders of the inputs. Any suggestions? C ...

Retrieving the timestamp of when each document was created

I am looking for a more efficient way to retrieve the creation date of each document in my find query. While I know there are some straightforward methods, I feel like there must be a better approach. Consider two possibilities: Include a timestamp fi ...

AngularJS Datepicker - calendar dropdown does not update when the model changes

I've been facing a challenge with the AngularJs datepicker in my project for some time now. Within my application, users have the option to either manually select a date using the calendar or click on "This Month" to automatically set the date to the ...

Tips on effectively utilizing a value that has been modified by useEffect

Here is my current code: const issues = ['x','y','z']; let allIssueStatus; let selectedIssueStatus = ''; useEffect(() => { const fetchIssueStatus = async() => { const response = await fetch(&ap ...