Modifying the size of an element with D3 when hovering with the mouse

In a previous project, I created a stacked bar chart with some interesting mouseover effects. Now, I want to take it a step further by changing the size of the rectangle that the user hovers over, returning it to its original size once they move away.

My aim is to have the rectangle resize on mouseover, so I started by attempting to adjust the height using this code:

.on('mouseover', function(d){
    d3.select(this).style("height", "110%");
})

I expected the rectangle to expand to 110% of its original height. However, instead of doing that, it ended up being 110% of the overall div's height. So, I tried a different approach using D3 selectors:

.on('mouseover', function(d){
    d3.select(this).style("height", d3.select(this).style("height")*1.10));
})

Unfortunately, this did not resolve the issue either, as there was no change in size. When logging the height of the element, it showed up as auto, indicating that I might be retrieving the height value incorrectly from the rect. What should be the correct syntax for obtaining the height?

EDIT: After experimenting with echonax's solution below, here's the full code snippet for the rect element in my stacked bar chart:

Jaar.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.y1); })
.attr("height", function(d) { return y(d.y0) - y(d.y1); })
.style("fill", function(d) { return color(d.name); })
.style("opacity", 1)
.on('mouseover', function(d){
    d.color = color(d.name);
    d3.select(this).style("opacity", 1);
    d3.select(this).style("height", height*1.1);
    d3.select(this).style("width", width*1.1);
    console.log(d3.select(this).style("width"));
    tip.show(d);
})
.on('mouseout', function(d) {
    d3.select(this).style("opacity", 0.6);
    d3.select(this).style("height", height);
    d3.select(this).style("width", width);
    tip.hide(d);
});

Answer №1

Utilize the following code snippet:

d3.select(this).attr("height", (y(d.y0) - y(d.y1))*1.1);

This will adjust the size to 110%.

If you try

d3.select(this).style("height")*1.10
, it won't work since d3.select(this).style("height") returns a String like "100px", for instance.

To achieve the desired result, you need to strip off the "px" from the String, multiply by 1.1, and then add "px" back at the end.

var newHeight = parseInt(d3.select(this).style("height"))*1.1 + "px";
d3.select(this).style("height", newHeight);

Answer №2

Check out this example on JSFiddle: http://jsfiddle.net/q5q6331p/16/

  .on("mouseover", function(d) { 
    d3.select(this).attr("height", function(d){
        return (y(d.y0) - y(d.y0 + d.y))*1.5
    });
  })
  .on("mouseout", function(d) { 
    d3.select(this).attr("height", function(d){
        return (y(d.y0) - y(d.y0 + d.y))
    });
  })

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

Tips for clearing out outdated information from a bar chart

My bar chart is receiving JSON data based on the selected dropdown value. The chart updates when the dropdown changes, but there seems to be a problem with the hover functionality causing the last visited value to shake the chart. Any suggestions on how ...

Utilizing JavaScript For Loops for Code Repetition

Apologies for the ambiguous question title - struggling to articulate this properly. Essentially, I have some JavaScript code that I am looking to streamline by using a for loop. $('.q1').keyup(function () { if ($.inArray($(this).val().toLo ...

Is it possible to interpret all events from multiple perspectives?

Is it possible to listen for events in three different ways? This example shows how we can listen for the load event: 1. <body onload="doSomething();"> 2. document.body.onload = doSomething; 3. document.body.addEventListener('load', doS ...

Passing no data in Angular.js ui-router.Angular.js ui-router

Within my Ionic application, there is a need to pass parameter(s) from one sub-view to another. Initially, the parameters are successfully passed as expected. However, upon returning to the first sub-view and then navigating to another sub-view, the parame ...

Managing a large number of records in a for loop on a Node.js server can be challenging, especially when dealing with nearly

After setting up a NodeJS server and connecting it to a MySQL database with around 5000 users, I needed to read the data from MySQL and update a MongoDB database. I managed to write code for this process. https://gist.github.com/chanakaDe/aa9d6a511070c3c78 ...

Receiving an unanticipated value from an array

Actions speak louder than words; I prefer to demonstrate with code: //global variable var siblings = []; var rand = new Date().getTime(); siblings.push('uin_' + rand); alert(siblings['uin_' + rand]); // undefined Why is it coming up ...

Error: react/js encountered an unexpected token

While attempting to execute my project, I encountered an error in the console related to a function within the code. The exact error message reads as follows: "63:25 error Parsing error: Unexpected token, expected (function toggleDrawer = (open) => () => ...

Is it conceivable to exploit JSON responses with appropriate JavaScript string escaping to launch an XSS attack?

Exploiting JSON responses can occur when Array constructors are overridden or when hostile values are not properly JavaScript string-escaped. To combat this, Google has implemented a technique where all JSON responses are prefixed with a specific code sni ...

Clicking to Load Images - Angular

Implementing a feature to load sets of images on button click instead of loading all at once. Although lazy load plugins are available, I decided to experiment with this approach. Here's the logic: Start with a data array called 'Images' co ...

"Trouble encountered while trying to display Angular in an HTML document

In my Angular project, there is a feature where a list of orders is displayed in one view. Each order is represented by its title only. When the user clicks on the title, they should be redirected to a new view showing the complete content of that particul ...

Change the color of the Material UI InputLabel

Seeking assistance with my input label: <InputLabel>NAME</InputLabel> The text is currently displaying in white, which makes it difficult to read against the white background. Can someone provide guidance on how I can change the color to blac ...

Creating curved triangles in React Native is a fun and easy way to add stylish

Hello everyone, I am a newcomer to react native and I am attempting to create the following user interface. Is there any way to create a curved triangle? I have tried but I am unable to curve the edges of the triangle. https://i.stack.imgur.com/vE17U.png ...

"Is there a way to retrieve a field from a different model within a Mongoose model

Presented below are two distinct MongoDB Models: Movie Model import mongoose from 'mongoose'; const movieSchema = new mongoose.Schema({ title: { type: String, required: [true, 'Please Enter the Movie Title'], trim: true, ...

Which approach yields better performance: setting all dom events simultaneously, or incrementally?

Is it more effective to attach event listeners permanently or only when needed? For example, consider a scenario where you have a dropdown menu in your HTML that opens when clicked. Within this menu, there is a close button that closes the menu upon click ...

Is it possible to update the variable value in one controller from another controller after an http.get request has been made

I have encountered an issue with updating a variable from one controller to another using a service. Despite my efforts, the variable is not being updated. The goal is to have the variable $scope.names in controller 'select' update in controller ...

What steps can be taken to address an unusual conflict arising between a form post and an ajax post

One web page features the use of ajax for editing existing values. This is achieved by utilizing jQuery Inline Edit to post new data, update records, and return with success. The process works well initially. Subsequently, I implemented the functionality ...

What is the best way to transfer data from a clicked table row to another component?

I am currently working on developing an email inbox component for a system where the emails are displayed in a table format. When a user clicks on a specific row, it should lead to another component for further details. Since the information is not rende ...

QuickCopy - Capture only what's in view

Hi there, I have a question: I'm trying to figure out how to make a button copy only the visible text within the element with id="description". Can someone help me troubleshoot? HTML: <p id="description"> Test <span style="display:none"> ...

Retrieve both the name and id as values in an angular select dropdown

<select (change)="select($event.target.value)" [ngModel]="gen" class="border border-gray-200 bg-white h-10 pl-6 pr-40 rounded-lg text-sm focus:outline-none appearance-none block cursor-pointer" id="gend ...

TinyMCE is deleting Bold tags in a numbered list when saving a form

I recently integrated the tinymce editor into one of my textareas, allowing users to format their text with options like bold, underline, and italic. Here is the implementation code: tinymce.init({ branding: false, statusbar: false, resize:true ...