What is the best way to update a canvas chart when the side menu is hidden?

I am facing an issue with the layout of my webpage, which includes a left side menu and a canvas chart.

The left side menu occupies the first 155 pixels of the width, leaving the rest for the canvas chart set to a width of 100%.

However, when I close the left menu, the chart does not automatically refresh to take up 100% of the available window width. It only refreshes when manually resizing the window.

The code snippet I am using is as follows:

<html>
<title>Test1</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<body>
    <div class="w3-sidebar w3-light-grey w3-card-4 w3-animate-left" style="width:155px; line-height:16px;" id="mySidebar">
        <div class="w3-bar w3-dark-grey">
            <span class="w3-bar-item w3-padding-16">Menu</span>
            <button onclick="w3_close_left_menu()" class="w3-bar-item w3-button w3-right w3-padding-16" title="close Sidebar">&times;</button>
        </div>
        <div class="w3-bar-block">
            <a class="w3-bar-item w3-button w3-border-bottom" href="regn.html">Test</a>
        </div>
    </div>
    <div id="main" style="margin-left:155px">
        <div class="w3-container w3-display-container">
            <span title="open Sidebar" style="display:none" id="openNav" class="w3-button w3-transparent w3-display-topleft w3-xlarge" onclick="w3_open_left_menu()">&#9776;</span>
        </div>
        <div style="padding-top:20px; padding-left:40px; width:100%;">
            DivFirst
        </div>
        <div style="padding-top:5px; padding-left:10px; padding-bottom:10px; width:98%; background-color: #11ffcc;">
            DivSecond
            <script type="text/javascript">
            window.onload = function() {;
                var chart0 = new CanvasJS.Chart("chartContainer0", {
                    legend: {
                        fontSize: 4
                    },
                    zoomEnabled: true,
                    toolTip: {
                        content: "{y} grader <br>{x}",
                        shared: false
                    },
                    axisX: {
                        gridColor: "Black",
                        gridThickness: 1,
                        interval: 1,
                        intervalType: "day",
                        interlacedColor: "#FCFCFF",
                        valueFormatString: "HH:mm - DD MMM",
                        labelFontSize: 14,
                        labelFontColor: "black"
                    },
                    theme: "theme1",
                    axisY: {
                        includeZero: false,
                        labelFontSize: 14,
                        labelFontColor: "black"
                    },
                    data: [{
                        type: "line",
                        lineThickness: 2,
                        showInLegend: true,
                        markerType: "square",
                        color: "#F08080",
                        xValueFormatString: "HH:mm - DD MMM YYYY",
                        legendText: "Inde temp",
                        dataPoints: [{
                            x: new Date(2017, 10, 3, 6, 30),
                            y: 22.15
                        }, {
                            x: new Date(2017, 10, 3, 7, 00),
                            y: 22.10
                        }, {
                            x: new Date(2017, 10, 3, 7, 30),
                            y: 21.89
                        }, ]
                    }, ],
                    legend: {
                        cursor: "pointer"
                    }
                });
                chart0.render();
            }
            </script>
            <script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
            <div id="chartContainer0" style="height: 400px; width: 99%;"></div>
        </div>
    </div>
    <script>
    function w3_open_left_menu() {
        document.getElementById("main").style.marginLeft = "155px";
        document.getElementById("mySidebar").style.width = "155px";
        document.getElementById("mySidebar").style.display = "block";
        document.getElementById("openNav").style.display = 'none';
    }

    function w3_close_left_menu() {
        document.getElementById("main").style.marginLeft = "0";
        document.getElementById("mySidebar").style.display = "none";
        document.getElementById("openNav").style.display = "inline-block";

        document.getElementById("chartContainer0").reload(false);
    }
    </script>
</body>

</html>

Within the 'w3_close_left_menu' function, I tried adding a line:

 document.getElementById("chartContainer0").reload(false);

However, this did not result in refreshing the canvas as intended.

Answer №1

If you haven't tested the code yet, it's highly likely that what you're missing is manually triggering the render() function on your chart after closing the menu in your w3_close_left_menu().

DOM elements don't always respond to resize events, but there are libraries available to provide cross-browser compatibility for this functionality.

Below is a suggested handler:

var menuButton = document.getElementById("openNav");
menuButton.addEventListener('click', function () {
    document.getElementById("main").style.marginLeft = "155px";
    document.getElementById("mySidebar").style.width = "155px";
    document.getElementById("mySidebar").style.display = "block";
    document.getElementById("openNav").style.display = 'none';
    chart0.render();
}, true);

Keep in mind that in your case, the w3.css file will apply transitions when opening and closing the menu. Therefore, you should listen for transitionend / animationend events on the animating element.

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

The alignment of h2 headings becomes disordered beyond a specific viewport width

Can someone help me with an issue I'm facing regarding the placement of my "rightside" navigation? The problem arises when the viewport width drops below 767px, causing the h2 elements in the rightnav to align themselves directly next to the #leftnav. ...

Passing parameters in a jQuery function through a button click

I am trying to figure out how to pass the @item.Id value as a parameter in the click function for a button. Here is the code snippet: <button id="buttonEdit" style="color:darkgreen" data-toggle="modal" data-target="#Ed ...

The Shopify cart.json request has encountered a setback with error 330

My current task involves using jQuery to retrieve cart data from Shopify, which I then display on another website. However, this process has suddenly stopped working. When I attempt to make the request in Google Chrome, it shows as 'failed' and u ...

Is there a way to trigger both the link and the div element simultaneously?

Is there a way to make both the button and the link light up simultaneously when hovering over the div element, instead of just the button lighting up first? <div id="b1"; class = b> <a href="test.html">BUY</a> < ...

Struggling to retrieve the JSON information, but encountering no success

Here is the javascript code snippet: $.getJSON("validate_login.php", {username:$("#username").val(), password:$("#password").val()}, function(data){ alert("result: " + data.result); }); And here is the corresponding php code: <?ph ...

Ensure that the method is passed a negative number -1 instead of the literal number 1 from an HTML error

This is an example of my HTML code: <button (mousedown)="onMouseDown($event, -1)"></button> Here is the TypeScript code for handling the mouse down event: onMouseDown(e: MouseEvent, direction: 1|-1) { this.compute.emit(direction); ...

Is there a way to exclude certain URLs from the service worker scope in a create react app, without the need to eject from the project?

Is there a way to remove certain URLs from a service worker scope in create-react-app without needing to eject? The service worker is automatically generated, and it seems impossible to modify this behavior without undergoing the ejection process. ...

Issue with integrating Bootstrap into Angular 2

When attempting to link to the bootstrap.css file located in the node_modules folder within index.html, I encountered an error. The application's folder structure is as follows: ecommerce-app/node_modules ecommerce-app/src/app/index.html All attem ...

Adjusting the starting position of text within an HTML <li> element

I am currently in the process of designing a webpage layout with three columns. I have a specific vision for how I want the text to align within these columns but I am unsure of how to achieve it. Is there a way to make the text start at an exact position, ...

Learn how to execute shell commands on a Linux server from a Node.js application by utilizing Socket.io for establishing a connection. This includes tasks such as running "ls -ltr", changing

After successfully establishing a connection with my Linux server, I aim to execute shell commands for automation purposes such as changing directories and creating new folders. The main objective is to connect to the Linux server through a webpage, wher ...

Error: Conversion of "2018-01-01-12:12:12:123456" to a date is not possible for the 'DatePipe' filter

<td>{{suite.testSuiteAttributes && suite.testSuiteAttributes.modifiedTimestamp | date: 'yyyy-MM-dd' }} </td> I am trying to display the date in the "05-Feb-2018 11:00:00 PM CST" CST format, but I keep getting an ...

The function .load callback was triggered on five separate occasions

I'm currently working with the code below and I have a feeling that I'm overlooking something important but just can't seem to figure it out. Basically, when the user clicks a button, a fragment of the page is loaded. Once this loading is s ...

When scrolling, use the .scrollTop() function which includes a conditional statement that

As a newcomer to jQuery, I've been making progress but have hit a roadblock with this code: $(window).scroll(function(){ var $header = $('#header'); var $st = $(this).scrollTop(); console.log($st); if ($st < 250) { ...

Mastering the art of reading rows in ASP.NET using Java Script

Within the code snippet below, you'll find an image located in the second column. Clicking on this second column should allow me to access the data stored in the first column. Let's say we have a table with 10 rows. If the user clicks on the ico ...

Is it possible to execute custom JavaScript code in an R Jupyter notebook?

Within my Jupyter Notebook, I am working with the R programming language and would like to integrate javascript functions into it. I'm aware that there are libraries in javascript that can be called from R, but I haven't been able to find any ex ...

Struggling to display my array data retrieved from the database on my Angular 5 page

I hope everyone is doing well. I am currently facing a problem with retrieving data from Firebase. I have an array within an array and I want to display it in my view, but I am encountering difficulties. Let me share my code and explain what I am trying to ...

Is there a way to adjust the saturation and desaturation of an image using CSS?

Issue Update After further testing, I have discovered that the desaturation effect is only functioning properly in Chrome. How can I adjust it to work in other browsers such as FF and IE? (Title modified) Currently, I am working on turning a color image ...

What is the best way to define the active <li> tab using JQuery?

Initially, my HTML code includes a set of <li> elements that I want to dynamically add to the existing <ul>. <ul class="tabs" id="modal_addquestion_ul"> <li class="tab-link current" data-tab="multipleChoice">Multiple Choice< ...

Form on the internet with a following button

Currently working on a basic form: <tr> <td> <label for="FirstName">First Name <span class="req">*</span> </label> <br /> <input type="text" name="FirstName" id="FirstName" class="cat_textbox" ...

Issue with v-model not connecting to app.js in Laravel and Vue.js framework

Snippet from app.js const app = new Vue({ el: '#app', router, data:{ banana:'' } }); Code found in master.blade.php <div class="wrapper" id="app"> <router-view></router-view> //using Vue ...