Enhancing tooltips in a multi-series chart with Highcharts - incorporating suffixes

Apologies for my lack of experience once again. I am now looking to enhance my tooltip by adding a suffix to indicate % humidity and °C for temperature. While the code derived from ppotaczek with some tweaks is working well, I've been struggling to add a valueSuffix due to multiple series (I plan to include more series later that will involve pressure symbols). I have attempted various ways to add a valueSuffix but it keeps returning undefined. I've tried using a variable in the series and valueSuffix but haven't managed to get it right. Any advice on this issue would be greatly appreciated.

Tooltip as it stands - suffix undefined

I hope my request is clear. Thank you in advance.

...

<?php $json_data = include('database.php');
?>
<!DOCTYPE HTML>
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Line Graph</title>

    </head>
    <body>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>


        <style type="text/css">
        #container {
            min-width: 310px;
            max-width: 800px;
            height:400px;
            margin: 0 auto
        }
        </style>

<div id="container"></div>


<script type="text/javascript">

var data = <?= $json_data?>

var series = [{
        name: "Temperature",
        valueSuffix: '°C',
        data: []

    },
    {
        name: "Humidity",
        valueSuffix: '%',
        data: [],
        yAxis: 1
    }
];
//alert(series[1].appendor);// from a previous attempt

data.forEach(function(dataEl) {
    series[0].data.push([
        new Date(dataEl.Timestamp).getTime(),
        Number(dataEl.temperature)
    ]);
    series[1].data.push([
        new Date(dataEl.Timestamp).getTime(),
        Number(dataEl.humidity)
    ]);
});

Highcharts.chart('container', {
     
    series: series,
    yAxis: [{
            title: {
                text: 'Temperature'
                
            }
            },
        {
            title: {
                text: 'Humidity'
            },
            opposite: true
        }
    ],
    title: {
      text: 'Temperature and Humidity',
      x: -20 //center
    },
    subtitle: {
      text: 'Source: The Caravan',
      x: -20
    },   
 tooltip: {
        formatter: function () {
            var suff = this.series.valueSuffix, heading = this.series.name
            return "<b>" + heading + "</b><br/>" + Highcharts.dateFormat('%a %d %b %H:%M.', this.x, true) + ":<br/>" + Highcharts.numberFormat(this.y, 0) + suff +" " ;
        },
        backgroundColor: 'rgba(0, 0, 0, .75)',
        borderWidth: 2,
        style: {
            color: '#CCCCCC'
        }
    },

 // fix for x-axxis from: https://stackoverflow.com/questions/7101464/how-to-get-highcharts-dates-in-the-x-axis 
   xAxis: {
    type: 'datetime',
    labels: {
      formatter: function() {
        return Highcharts.dateFormat('%a %d %b', this.value);
      }
    }
  },
 
});

</script>

</body>

</html>

...

Below is an excerpt of the json_data fetched from a dynamic MySQL database: [{"Timestamp":"10:04 02/01/21","temperature":"5","humidity":"66"},{"Timestamp":"10:19 02/01/21","temperature":"6","humidity":"65"},...]

Answer №1

In a series, the valueSuffix property is not directly stored as it is a custom one and saved in the series.options.

    tooltip: {
        formatter: function() {
            var suff = this.series.options.valueSuffix,
                heading = this.series.name;

            return "<b>" + heading + "</b><br/>" + Highcharts.dateFormat('%a %d %b %H:%M.', this.x, true) + ":<br/>" + Highcharts.numberFormat(this.y, 0) + suff + " ";
        },
        ...
    }

Check out the live demonstration here: http://jsfiddle.net/BlackLabel/1se5cyd7/

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

Utilizing the props value for emission within the emits array: A guide

While attempting to list a custom event in the component's emits option, I encountered a console error. The code looked like this: PARENT <Btn event-name="toggleSideMenu" @toggle-side-menu="toggleHandler"> togg ...

Errors in JavaScript are displayed when a React application is built for production

I have developed a client react application using create-react-app. It communicates with a node server that runs an express api. During development, everything was smooth sailing and I was preparing for deployment. After running npm run build, there were ...

A JSON request is being processed within a while loop

Attempting to complete what I initially thought was a simple task has led me to believe that I may have oversimplified the process or made a mistake in my loop. My objective is to browse through a series of links containing JSON objects in order to identif ...

Transform JavaScript code to integrate with a pre-existing WebSocket within a React.js application

I have created a JavaScript code to establish connections with my own Ruby WebSocket server, where it waits for incoming messages, parses them, and then displays content based on certain conditions (the implementation details are not relevant at the moment ...

Looking for tags similar to stackoverflow?

Is there a way to create a search box similar to the one in Tags where tag names are displayed immediately upon entering without pressing enter key? Could anyone provide me with a script or tutorial on how to achieve this? Is it done using JavaScript or j ...

You are unable to establish headers once they have already been sent to the client, as indicated by the error

Github : https://github.com/UJJWAL2001/Pro-Shop/tree/main/backend My current objective is to implement JWT token for securing my routes using the middleware provided below import jwt from 'jsonwebtoken' import User from '../models/userModel ...

Grails 3.1.9 does not support displaying JavaScript

Having trouble getting the datepicker to display using JavaScript <script> $( "#invoiceDate" ).datepicker({ inline: true, dateFormat: "yy-mm-dd", onSelect: function(datetext){ datetext = datetext+" 00:00:00.0" ...

Whenever I try to launch my React app using the `npm start` command in my command

After successfully creating a Simple React App and getting the happy hacking message on cmd, I encountered numerous errors when trying to run "npm start" on cmd. Despite multiple attempts at uninstalling and reinstalling node and npm, the issue persists. H ...

Is there a way to repeatedly call a function without losing its previous outputs, without relying on a database? What alternative should I consider using instead?

I'm looking to create multiple tables using the same function in JavaScript. However, when I call the function again, the previous table disappears. I am new to coding in JavaScript and would appreciate any suggestions on how to handle this issue. I p ...

What is the most effective method for storing an object in React?

I am facing an issue with storing my Object of my Checkout-Cart in a React Variable. I attempted to use the useState Component, but unfortunately, it did not work. Here is the object that I receive from my NodeJs Backend : [ { product_uuid: '3b ...

How to use the window.confirm method to print the HTML tag in an AJAX post

Is there a way to display a confirmation window for users who want to delete data from the database without including HTML tags like <strong> or <br />? I am currently using the confirm() function as follows: var str = document.getElementById ...

Switch between using the useState hook by toggling it with the MUI Switch

Looking to implement a custom Dark Mode feature for a specific element on my create-react-app website using MUI. I have successfully implemented the Switch to change the state on toggle, but I am having trouble figuring out how to toggle it back and fort ...

onload function prevents further URL redirection

After submitting the form "View this product," a function is triggered to retrieve the product id from the form data. Although I can successfully obtain the form_data, the page does not redirect as expected. I suspect that my function may not have been pr ...

Issues arise when JQuery functions fail to execute

This unique program showcases a series of error messages that are designed to appear under specific conditions. These conditions are identified through PHP code, following which the essential JQuery script is echoed via PHP to display the messages. Initia ...

React: Remember to always retain the initial four characters when making changes

I have implemented an input component for phone numbers using the react native phone input library, which automatically adds the international code. However, I am facing an issue where the international code +234 is deleted when the user presses the back b ...

Executing a secondary API based on the data received from the initial API call

Currently, I am diving into the world of RxJS. In my project, I am dealing with 2 different APIs where I need to fetch data from the first API and then make a call to the second API based on that data. Originally, I implemented this logic using the subscri ...

What are the best ways to make this date more visually appealing and easy to understand?

Hey there! So I have a date that looks like this: 2022-06-28T17:09:00.922108+01:00 I'm trying to make it more readable, but unfortunately, when I attempted using moment-js in my javascript/react project, it threw an error stating "invalid format". ...

Using PHP to upload images through AJAX increases efficiency

Worked tirelessly on this script all night still unable to fix the bug. The issue is that when I select an image and click upload, it uploads the current image file. Then, if I select another image and click upload, it uploads two new files along with the ...

Update the React component without needing to reload the entire webpage

Every time I attempt to render a new component, the entire page refreshes instead of just the components re-rendering. Upon loading the page, when I click the drop down menu in the header, it successfully renders a new component without any refreshing. Ho ...

Having difficulty adding information to MySQL database table

There are two sets of information below. Set 1: "We have just completed the main phase of developing version 9.8 and it is now in the testing and preparation stage. While you wait for the release, we encourage you to learn more about what exciting featur ...