HTML button's "onclick" attribute calls function before being clicked on

Viewed 194

I am trying to use d3.select to create a button in the DOM with an onclick attribute so that when I click on the button, some function is called. However, before I click on the button, the function just calls itself. Here is my JS code:

var something = function() {
     console.log("do something");
}


d3.select("#done")
    .append("button")
    .text("Button Text")
    .attr("onclick", something);

and here is my HTML (there's more than this but this is the relevant part):

<div id="done"></div>

When I execute the code, the something function is immediately called and prints to the console. How can I fix this?

Apologies in advance if this seems really naive--I am very new to this.

1 Answers

Instead of using attr("onclick", something), which will immediately call the function, set the event listener using selection.on:

var something = function() {
  console.log("do something");
}

d3.select("body")
  .append("button")
  .text("Button Text")
  .on("click", something);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

For you to understand why something was called in your code, even if it has no parenthesis (like something()), the documentation for selection.attr explains that:

[...] if the value is a function, it is evaluated for each selected element.

That being said, you're evaluating the function (and, therefore, logging a message in the console). Also, have in mind that your function returns undefined and therefore you're not adding any attribute.

Related