Disabling Highchart datalabels when the window is resized

While attempting to implement a pie chart using Highcharts, I have encountered an issue with the datalabels getting cropped on very low resolutions.

I tried adding a windows.resize within the formatter function but it did not work.

Below is the current code snippet I am using:


// Radialize the colors
Highcharts.getOptions().colors = $.map(Highcharts.getOptions().colors, function (color) {
    return {
        radialGradient: { cx: 0.5, cy: 0.3, r: 0.7 },
        stops: [
            [0, color],
            [1, Highcharts.Color(color).brighten(-0.3).get('rgb')] // darken
        ]
    };
});

// Build the chart
chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        backgroundColor: {
            linearGradient: [0, 0, 500, 500],
            stops: []
        },
    },
    title: {
        text: 'Header Here'
    },
    tooltip: {
        pointFormat: '{series.name}: <b>{point.percentage}%</b>',
        percentageDecimals: 0
    },
    plotOptions: {
        pie: {
            allowPointSelect: false,
            cursor: 'pointer',
            dataLabels: {
                enabled: true,
                color: '#000000',
                connectorColor: '#000000',
                formatter: function() {
                    return '<b>'+ this.point.name +'</b>: '+ Math.round(this.percentage) +'%';
                }
            }
        }
    },
    series: [{
        type: 'pie',
        name: 'Votes',
        data: [
            ['Vote One', 50],                   
            ['Vote Two', 50],
            ['Vote three', 2]
        ]
    }]
});

Is there any other way besides creating a new chart on resize to hide or show the labels based on resolution?

Thank you.

Answer №1

If you want to customize datalabels in Highcharts, you can set useHTML to true and define your own div structure in the formatter function. Then, you can use show/hide functions to toggle the visibility of the datalabels when a resize event is triggered.

For a simple example demonstrating how to show/hide datalabels after clicking a button, you can visit this link:

http://jsfiddle.net/VYGEW/

chart = new Highcharts.Chart({
        chart: {
            renderTo: 'container',
            type: 'line'
        },
        title: {
            text: 'Monthly Average Temperature'
        },
        plotOptions: {
            series: {
                dataLabels: {
                    enabled: true,
                    useHTML: true,
                    formatter: function () {
                        return '<div class="datalabel">' + this.y + '</div>';
                    }
                }
            }
        },
        series: [{
            data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
        }]
    }, function (chart) {

        $('#btn').toggle(function () {

            $('.datalabel').hide();
        }, function () {
            $('.datalabel').show();
        });

    });

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

Using the viewport meta tag in HTML and CSS within Laravel's Blade template while also

Greetings everyone! I have a question regarding Blade Laravel: Can we add a condition to the meta name="viewport" content="width=device-width, initial-scale=0.4"? I want the scale to start at 0.4 for smartphones and at 0.6 for tablets. ...

Can one manipulate the simulation to make isTrusted=true a reality?

Is there a way to simulate an isTrusted=true in touchStart event triggering? Are there any libraries or workarounds that can make this achievable? When I run the touchStart event programmatically versus physically triggering it, the output differs. Below ...

Use jQuery AJAX to load HTML content from previously loaded HTML using another AJAX request

I'm working on creating a Wiki-like structure by loading external HTML code into my base-page using jQuery and AJAX. While I've been successful in loading html content into specified divs, I've run into an issue with links within the loaded ...

Modifying a Sass variable using a Knockout binding or alternative method

Is it feasible to dynamically alter a sass variable using data-binding? For instance, I am seeking a way to modify the color of a variable through a button click. I am considering alternative approaches apart from relying on Knockout.js. $color: red; ...

Encountering an unexpected token in Javascript when using conditionals

I am currently attempting to integrate a JavaScript condition within a listed order, containing two radio buttons that need to be checked in order to progress to the following list based on the selection. <li data-input-trigger> <label class="fs- ...

Increase the size of a button using CSS styling

Looking for guidance on extending the length of a button in HTML code? Take a look at this snippet: <span class="xp-b-submit xp-b-submit-btn xp-b-right"> <a href="#" class="xp-t-bold" id="PostSubmitLink">Post Search</a> </span> ...

Show error message and display in ajax response

Hey there! I have a question about using Ajax to send error messages if an error occurs, otherwise sending the view. Here is my code snippet and I would really appreciate some guidance or suggestions on what to do next: Here is an example of my code: pub ...

When the parent div contains at least four divs, show the scroll arrow containers

In my code, there is a parent div that holds multiple child divs. If the number of child divs within the parent div exceeds 4, I want to show the scroll arrow containers. If it's less than 4, then those arrow containers should not be displayed. The ...

How can I ensure my screen updates instantly after modifying an image's source using Javascript?

My goal is to display a new image in an existing <img> tag by updating the src attribute using JavaScript. The issue I'm facing is that the screen doesn't immediately reflect the change when the src is updated with the URL of a thumbnail im ...

Have you ever wondered how the automatic video play on scroll feature works on Tiktok.com and YouTube shorts when using a mobile device?

My goal with React JS is to develop a website similar to Tiktok, where the video below will automatically play with sound as the user scrolls down. I attempted to set this up using window.addEventListener("scroll",...), but after looking into it further, ...

When a promise is executed, it runs the code synchronously regardless of the promise

Essentially, I have a web application that fetches data from Firebase. Due to the time it takes to retrieve this data, I've implemented promises in JavaScript to ensure my code executes at the appropriate times. Within the function getDataFirebase, in ...

The reload/refresh feature for images is not functional

When generating images automatically, I noticed that the file with the same name gets updated but is not reflected in the browser. $("#image_test").attr("src", data) I have tried: d = new Date(); $("#image_test").attr("src", data+d.getTime()); , $("#i ...

Binding data to buttons in Asp.net core

I'm currently studying ASP.NET Core MVC and I have a model that looks like this: public class Todo { public int Id { get; set; } [Required] public string Name { get; set; } [MaxLength(4096)] public string Content { get; set; } ...

The jQuery event binding feature functions properly with simple text links, but does not work when used with links

Having some trouble with my jQuery code. <script type="text/javascript> jQuery.noConflict(); jQuery(document).ready(function(){ jQuery('a.connect').bind("click", function(event) { var st ...

Error: The function $.simpleTicker is not defined

Every time I try to call a jQuery function, an error shows up: Uncaught TypeError: $.simpleTicker is not a function I attempted changing $ to jQuery but it didn't resolve the issue. This represents my jQuery code: (function ($) { 'use ...

Tips for aligning text and an image next to each other within a table column using HTML

I have a table where I am displaying an image and text in separate columns, with the image above the text. However, I want to showcase them side by side and ensure that the table fits perfectly on the screen without any scroll bars. Here is my HTML code s ...

Is it possible to utilize promises to execute a function once the initial one has completed its task?

I am struggling to wrap my head around promises. Currently, I am working on a project where I scrape a website using node and NPM, then save the data to a CSV file. While I can successfully retrieve the data with multiple scrapes, I want to ensure that th ...

How can I use JQuery to sum up the numbers within div elements?

Is there a way to automatically number the generated blocks? For example, the first block would display "1", the second "2" and so on. Below is my current code. Simply input the desired number of blocks in the input field. <!DOCTYPE html> <html ...

Utilizing jQuery's each() function to create a seamless loop of background images in a

Struggling with looping the background image in a slick slider? Check out the code snippet below. var json = [ { "img_url": "https://via.placeholder.com/500x500?text=1" }, { "img_url": "https://via.placeholder.com/500x500?text=2" }, { "img_url": "ht ...

CSS - text featuring a gentle shadow hue and a deeper foreground color

I'm encountering an aesthetic issue where my list of texts have random light/bright colors, making them hard to read on white backgrounds. I've tried setting the text color to shadow, but now I want the text itself to be a darker, more readable c ...