d3.on event firing prior to mouseover event

This page showcases a dynamic d3 bar chart. On line 162, we have an interesting event listener that logs a message when the user hovers over a bar on the chart. However, the log is displayed as soon as the page loads.

You can see the running code in action here:

If you are interested in delving into the full code, it's available on GitHub: https://github.com/shanegibney/d3Mouseover

The code includes HTML and JavaScript snippets for creating an interactive visual representation based on sample data showcasing different swimming sessions.

Although efforts were made to bind the hover effect only to specific elements related to the chart bars, there seem to be challenges with integrating brushX() and zoom functionalities seamlessly within the context.

Answer №1

When you perform the following action:

.on("mouseover", console.log("I am on it"))

You are actually passing the output of the console.log function to the callback. Instead, what you should be passing is the function reference itself:

.on("mouseover", function(){
    console.log("I am on it")
})

Take a look at this example (but do not hover over the circle!):

var circle = d3.select("circle");
circle.on("mouseover", console.log("I'm on it!"));
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
  <circle cx="50" cy="50" r="15" fill="teal"></circle>
</svg>

Now, let's rewrite the same code using the reference to console.log:

var circle = d3.select("circle");
circle.on("mouseover", () => console.log("I'm on it!"));
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
  <circle cx="50" cy="50" r="15" fill="teal"></circle>
</svg>

Answer №2

The problem arises when the function is being called at the same time as it is being declared:

.on("mouseover", console.log("I am currently on it")) //function call 

A better practice would be to write it like this:

.on("mouseover", console.log) //function reference
.on("mouseover", function(d) { console.log("I am currently on it") }) //function reference

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

Update the contents of a div element with JavaScript and PHP combo

When I click on the following div, I want to replace it with a similar one from file.php. The div tag in question is: <div style="display: none;" id="extra" class="container2" xml:id="page"> <div class="title"> <h2>Stuff to check out< ...

Tips on dividing the information in AngularJS

Sample JS code: $scope.data={"0.19", "C:0.13", "C:0.196|D:0.23"} .filter('formatData', function () { return function (input) { if (input.indexOf(":") != -1) { var output = input .split ...

Accessing AngularJS variable scope outside of a function

Utilizing a socket, I am fetching data into an angularJS controller. $rootScope.list1= ''; socket.emit('ticker', symbol); socket.on('quote', function(data) { $rootScope.list1 = angular.fromJson(data.substring(3)); //I can ...

Personalize your message in a JavaScript alert using Bootstrap notifications

On numerous websites, a new visitor landing on the page is greeted with an alert notification that pops up in either the bottom right or left corner. The code below functions perfectly fine, except for my unsuccessful attempts to change the message text w ...

Error: The function .default.auth.signout is not recognized in the REACT and Firebase environment

I've come across several error questions on StackOverflow, but most remain unanswered. The ones that are answered don't seem to solve my issue. I need help debugging this particular error. In my REACT project using Firebase, I'm working on ...

"Enhance Your Website with jQuery: Organized Lists with Fixed Length, Connected,

I currently have a list that is separated into three columns, structured as follows: Column1 Column2 Column3 1 4 7 2 5 8 3 6 9 The list ranges from 1 to 9 and each column consists of a fixed number of rows (3). I am lo ...

Is there a way to determine the negative horizontal shift of text within an HTML input element when it exceeds the horizontal boundaries?

On my website, I have a standard HTML input field for text input. To track the horizontal position of a specific word continuously, I have implemented a method using an invisible <span> element to display the content of the input field and then utili ...

Learning how to effectively incorporate two matSuffix mat-icons into an input field

I'm currently experiencing an issue where I need to add a cancel icon in the same line as the input field. The cancel icon should only be visible after some input has been entered. image description here Here's the code I've been working on ...

What could be causing a momentary 404 error when I click on a next.js `Link` that connects to an API endpoint before redirecting to the intended page?

Hello there, I recently followed a tutorial on adding authentication with Passport to Next.js from this resource: https://auth0.com/blog/next-js-authentication-tutorial/ However, I encountered a minor issue. When I click the "/login" Link in my Next.js ...

Is there a way to utilize a variable as a key within an object?

Can this be done? Take a look at a practical example from the real world: var userKey = "userIdKey"; chrome.storage.sync.set({ userKey: "Hello World" }, function () { chrome.storage.sync.get(userKey, function (data) { console.log("In sync:", ...

How to use jQuery to locate and update the final parameter of a URL

Hello everyone, I've already done some research but couldn't find a solution that fits my needs. Can anyone assist me with this? I currently have a URL "/view/album/4/photo/1" and I am looking to remove the final parameter and replace it with so ...

What is the best way to create a TypeScript function similar to a 'map' in React?

I recently started learning TS and am having trouble typing this arrow function: const mapLikeGet = (obj, key) => { if (Object.prototype.hasOwnProperty.call(obj, key)) return obj[key] } ...

nyroModal automatically adapts its dimensions according to the size of the webpage, not the size of

A situation has arisen with a link that opens an image using nyroModal. While everything is functioning correctly, the Modal window appears in the center of the page instead of aligning with the middle of the browser window. As a result, only the upper por ...

Creating a comparison display using ng-repeat

I have a JSON file that contains revision and history information about a modified entity, including its old and new values. The diff is generated using the jsondiffpatch library and I have parsed it further to create the final JSON format for rendering. ...

Loading page with asynchronous JavaScript requests

As I send my AJAX request just before the page loads and then call it on the same page afterwards, here is what it looks like: <input type="text" class="hidden" id="storeID" value="<?php echo $_GET['store']; ?>"> $(document).ready(fu ...

Using Switch Case and If Statements in Javascript and Jquery

Can you help me troubleshoot this code? It's designed to detect clicks and keypress events within the #ts_container div for buttons and anchors. The goal is to use an If statement in each case to determine if it's a click or keypress, then update ...

Monitor checkbox status to trigger confirmation dialog

My goal is to prevent the checkbox from changing if 'NO' is clicked in a dialog. The dialog pops up, but I can't figure out how to wait for it to close before allowing the checkbox change. I've attempted using Promises and doing everyt ...

Snippets of the webpage peeking through before the Fakeloader takes over

After implementing fakeloader to preload my content here, I have noticed that my site header often appears before the fakeloader preload animation completes. Is there a way to delay showing the content until the fakeloader is finished loading? Here is the ...

How can I pass function arguments dynamically to a nested function in Node.js?

Currently using Node 6.11.0, I am attempting to accomplish the following dynamically: const parentFunc = (arg1, arg2, arg3, arg4) => { childFunc('foo', arg1, arg2, arg3, arg4); }; I have attempted this method (without success): const pare ...

JavaScript incorrectly constructs date strings

Hey there, I've been attempting to create a JavaScript date object using a string but for some reason, it's consistently off by one day. Every time I try, it ends up showing the wrong day. Below is the code snippet in question: var date = new Da ...