Is it possible to align a div outside the canvas to the axes using Chart.js?

Chart.js uses a canvas to render its axes. Beneath the canvas, there is a div that holds a control element, such as an input slider.

I am looking to adjust this div by adding a margin or another method so that it aligns itself not with the canvas, but with the axes inside it. This would mean that the width of the slider within the div matches the width of the axes.

Is there a way to achieve this?

https://i.sstatic.net/uMVjo.png

Answer №1

Solution For Chart.js Canvas

  • To enhance the chart.js canvas provided below:
  • Adjust the y axis width to 50px in this case
    options: {
        scales: {
            y: {
                afterFit: function (scaleInstance) {
                    scaleInstance.width = 50; // sets the width to 50px
                }
            }
        }
    }

  • Utilize a known value for setting graph width via slider input
const sliderToPercentageWidth = (sliderVal) => {
    return (50 + (containerWidth - 50) * (sliderVal/100) )
};
  • Maintain containerWidth on window resize with following script
window.addEventListener("resize", (event) => {
    containerWidth = container.offsetWidth;
});

The snippet below encompasses all elements, accessible through (CodePen link):

HTML

<div id="container">
    <div id="graph">
        <canvas id="myChart"></canvas>
    </div>
    <input id="width-selector" type="range" value="50">
    
</div>

CSS

#container{
    background-color: #ff000020;
    width: 80vw;
    height:90vh;
}

#graph{
    height: 70vh;
    width: 40vw;
    background-color: #00ff0020;
}

#width-selector{
    width: calc(100% - 50px);
    margin-left: 50px;
}

JS

const sliderToPercentageWidth = (sliderVal) => {
    return (50 + (containerWidth - 50) * (sliderVal/100) )
};

const rangeInput = document.getElementById("width-selector");
const graph = document.getElementById("graph");
const container = document.getElementById("container");
let containerWidth = container.offsetWidth;

// Match the slider width to graph on first render
const newWidth = sliderToPercentageWidth(rangeInput.value)
graph.style.width = `${newWidth}px`;

window.addEventListener("resize", (event) => {
    containerWidth = container.offsetWidth;
});

rangeInput.oninput = () => {
    const newWidth = sliderToPercentageWidth(rangeInput.value)
    graph.style.width = `${newWidth}px`;
};


// A basic chart
// Option for y axis width set

const ctx = document.getElementById("myChart");

new Chart(ctx, {
    type: "bar",
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [
            {
                label: "# of Votes",
                data: [12, 19, 3, 5, 2, 3],
                borderWidth: 1
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
            y: {
                afterFit: function (scaleInstance) {
                    scaleInstance.width = 50; // sets the width to 50px
                }
            }
        }
    }
});

Prior Incorrect Solution

You can monitor slider input changes using JS and update graph CSS styling accordingly.

Here's a basic setup example considering slider value mapping to graph width.

The HTML and CSS are minimalistic, dynamically adjusting the width based on the slider input.

<div class="container">
    <div id="graph"></div>
    <input id="width-selector" type="range" value="50">
</div>
.container{
    background-color: red;
    width: 50vw;
    height:70vh;
}

#graph{
    height: 50vh;
    /* Initialize width according to the input slider */
    width: 50%; 
    background-color:blue;
}

#width-selector{
    width: 100%;
}
const rangeInput = document.getElementById("width-selector");

const graph = document.getElementById("graph")

rangeInput.oninput = () => {
    graph.style.width = `${rangeInput.value}%`
}

If your code structure differs from this example, feel free to share for specific guidance.

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

Incorporating JSON data on-the-fly into a space tree visualization

I'm currently utilizing spacetree js to display the tree view. My goal is to dynamically load the json data after clicking on a node. I have tried running the sample examples with hardcoded json values. However, I am unsure of how to make it more d ...

What causes the CSS `resize` property to be inherited in Chrome browsers?

It was my understanding that elements do not inherit the resize property from their parent elements. However, I recently discovered that in Chromium they actually do: Here is a screenshot of Chromium's inspector: Check out this demo: http://jsfi ...

Causes for the display of the text within the alt attribute

Recently, I attempted to view an HTML page in text browsers and noticed that the alt attribute value of the img tag was visible. I decided to omit the alt attribute and instead utilized CSS: .headerImg:after, .headerImg::after { conte ...

The checkbox styles in Tailwind CSS seem to be malfunctioning and are not

In my Next.js project, I encountered an issue with a checkbox where certain Tailwind utility classes were not being applied. Despite trying to modify the color, background, and border properties, nothing seemed to change except for width, height, and curso ...

Tips on inserting table data into a textarea input using a button

Is there a way to display the text from the table in a textarea box when clicking the "add" button, without removing the data once it's added? I simply want the text "Add this text to textarea" to show up in the textarea box. https://jsfiddle.net/bj ...

React Error: Unable to iterate over this.state.descriptions

Currently facing an issue while trying to resolve this error https://i.stack.imgur.com/BZ304.png The goal is to generate an automated form using the following function: let descriptionsForm = ( <form> {this.state.descriptions.map((d ...

Error: The carousel in Bootstrap is throwing a TypeError because f[0] is not

We are currently utilizing Bootstrap Carousel to load dynamic slides, with each slide corresponding to an item in an array. AngularJS is employed to create the array and iterate through it. However, during execution, we encountered a javascript error Type ...

Exploring the concept of using variables and understanding variable scope in AJAX and JavaScript

Struggling with using variables in AJAX. Attempting to have var x store data from var data but it keeps showing as undefined in the console log. Any tips on how to fix this issue? EDIT: The variable x needs to be accessed later in the code, not just for ...

Retrieve an array from the success function of a jQuery AJAX call

After successfully reading an rss file using the jQuery ajax function, I created the array function mycarousel_itemList in which I stored items by pushing them. However, when I tried to use this array in another function that I had created, I encountered t ...

Looking to have the content aligned in the center of the parent container while also

Below is the code snippet I am working on, which utilizes Bootstrap 4: .resource{ border:1px solid red; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxP ...

Issues arise when attempting to animate letters using jQuery and CSS

My goal is to create a dynamic animation effect on a string when a user hovers over it. This involves turning the string into an array and applying different animations to each letter. Although the animations are working perfectly, I'm facing one issu ...

Show a selection of assorted files stored in the database

router.get("/alw", function(req, res){ Product.find({"category": "alw"}, function(err, allProduct){ if (err){ console.log(err) } else { res.render("products/alw", {products ...

Modifying the CSS for a single page - specifically the contact us page - on a WordPress website

Recently, I developed a Wordpress website for a client. However, the client has a unique request - they want the Contact Us page to have a different design compared to the other pages on the site. I attempted to create a separate CSS file for the Contact ...

You cannot use a colon ( : ) in HTML input text fields

How can I prevent a colon from being inserted into an input text field? In my code snippet, I have <input type="text"/> and I want to ensure that if the user types " : ", nothing appears in the input text field. Is there a way to achieve this using ...

Is it necessary for TypeScript classes that are intended for use by other classes to be explicitly exported and imported?

Is it necessary to explicitly export and import all classes intended for use by other classes? After upgrading my project from Angular 8 to Angular 10, I encountered errors that were not present before. These issues may be attributed to poor design or a m ...

How can I dynamically update an img src using JavaScript on a PHP webpage?

I have a PHP page where I display image thumbnails. I am trying to implement a feature where the thumbnail expands in another image on mouseover. Here is the PHP code snippet: echo "<tr><td><a href='$imgrow[location]' target=&ap ...

Tips for populating an HTML input with the value of a link element using JQuery

I have a form input that I want to populate with autocomplete suggestions from my database using Ajax. To style the list, I am using bootstrap 4, and I have opted to use the <a></a> tag instead of the <li></li> tag. This is because ...

Extracting null data from web scraping using Python and Beautiful Soup

I'm currently facing challenges with extracting the correct values from a website that provides prices for Silver, Gold, Palladium, and Platinum. You can find the website here. Below is the HTML structure of the website: <div id="header-tab ...

experiencing a never-ending loop while attempting to load images through ajax requests

I am attempting to ensure that user uploaded files remain private in node.js. I am utilizing angular to display the file on the client side. <div ng-repeat="message in messages"> <div class="details" ng-if="message.type == 'photo'"& ...

Handlebars: Access to the property "some prop" has been denied as it is not considered an "independent property" of its parent object

Model of MongoDB: const mongoose = require('mongoose'); const ProductSchema = mongoose.Schema({ _id:mongoose.Schema.Types.ObjectId, Pid:Number, Pname:String, Price: Number, Pdesc: String, Picname: String }); module.ex ...