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

What is the best way to keep the navbar contained within the parent div (hero image) no matter the size of the screen?

After working on adjusting my website layout for different screen sizes, I encountered an issue with the navbar overflowing the parent image when viewed on my laptop. Despite trying both relative and absolute positioning for the .navbar element and setting ...

When attempting to add objects to an indexedDB object store, an InvalidStateError is encountered

I have defined IndexedDB and IDBTransaction dbVersion = 1; var db; var dbreq; var customerData = { ssn: "444", name: "Bill", age: 35, email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2b0bbbebe92b1bdbfa2b3bcabfcb1bdbf"& ...

Navigating within two containers using the anchorScroll feature in AngularJS

I am trying to create a page with two columns of fixed height. The content in each column is generated using ng-repeat directive. Is it possible to implement scrolling within each column to a specific id using AngularJS? Code <div> Scroll to a p ...

What is the best way to show JSON array data in jQuery without using double quotes?

I have encountered an issue where I need to remove the double quotes from my json_encode output. To achieve this, I have used the following code: $json_string = json_encode($data); $json_string = str_replace('"','',$json_string); echo ...

Streamlining programming by utilizing localStorage

Is there a more efficient way to streamline this process without hard-coding the entire structure? While attempting to store user inputs into localStorage with a for loop in my JavaScript, I encountered an error message: CreateEvent.js:72 Uncaught TypeErr ...

Obtain user input and extract the name using jQuery's serialization function

Trying to extract user input from a dynamic form using jquery serialize. The structure of my form is as follows: <form id="lookUpForm"> <input name="q" id="websterInput" /> <button onclick="webster(); return ...

Extract data from nested JSON and populate a list with corresponding values

<ul> <li><a href="" class="edit">a unique item in the list</a></li> <li><a href="" class="edit">another unique item in the list</a></li> <li><a href="" class="edit">yet another unique ...

Identifying the differences between a select2 dropdown and select2 multiselect: a guide

I currently have two different controls on my page: a select2 dropdown and a jquery multi value select Select2 Dropdown <select id="drp_me" class="select2-offscreen"> <option value="1">one</option> <option value="2">two</op ...

Retrieve information from the Next API within the getStaticProps function in a Next.js project

In my Next.js project, I encountered an issue where fetching data in getStaticProps() worked perfectly during local development but resulted in an error during next build. The error indicated that the server was not available while executing next build. Fe ...

If a specific class is identified, add a border to the div when clicked using JavaScript

Is there a way to use javascript/jquery to add a border to a selected div? I have multiple rows with columns, and I want only one column per row to be highlighted with a border when clicked. Each row should have one column with a border, so it's clear ...

Progress Bar Countdown Timer

I have made some progress on my project so far: http://jsfiddle.net/BgEtE/ My goal is to achieve a design similar to this: I am in need of a progress bar like the one displayed on that site, as well as the ability to show the days remaining. Additionally ...

Why was the express.js boilerplate code created?

As a newcomer to Node and Express, I am curious about the purpose of the boilerplate directories that are automatically generated when setting up an express project. I have searched online for explanations on the significance of these files without much l ...

Change the way a button interacts with a different element

Currently, I am utilizing SlickSlider from http://kenwheeler.github.io/slick/ and attempting to integrate the Next and Prev buttons with other elements (specifically spans within another container). I have attempted the following: $('button.next&apo ...

Tips for resolving the trigger problem with onChange in the PinInput Component of chakra-ui

The PinInput Component's onChange event is not functioning properly with the value in Chakra-UI. This issue causes the focus to automatically shift to the next input even when the value hasn't changed. For instance, when attempting to set the st ...

What is the best pattern to utilize for these types of tasks?

I've been struggling a bit with understanding the MVC principle, but I always believed that business logic should be contained within models - please correct me if I'm mistaken. In my current project, I am following the MVC pattern. The rou ...

Encountering a type error when attempting to assign an interface to a property

In my Angular project, I am working with typescript and trying to assign the IInfoPage interface to some data. export interface IInfoPage { href: string; icon: string; routing: boolean; order: number; styleType: string; ...

Developing a side panel for navigation

My goal is to create a sidebar that shifts to the right from the left side and makes space on the page when the hamburger menu is pressed. I have made progress in achieving this, but I am encountering difficulties with the animation. const btnToggleSide ...

Challenges in the Knockout Framework Due to Synchronization Issues

Recently, I've encountered a slight problem with race conditions in my code. Utilizing Knockout.Js to collect information for user display has been the cause. The issue arises when a dropdown needs to be created before a value can be selected. Typica ...

The function document.getElementById(...) is failing to retrieve the text data from the table as expected

Greetings fellow HTML and JavaScript novice! I've got a table with input cells in the bottom row: <table class="convtbl" id="table1"> <tr> <td>Distance 1 (in miles)</td> <td>Time ...

JQuery does not allow for changing the selection of a RadioButtonFor

I am currently working on a code that determines whether or not to display contact information. To achieve this, I am using the RadioButtonFor html-helper with a boolean value for the MVC view model in Razor. Upon loading the page, I need to switch from t ...