Search code examples
imaged3.jsinnerhtmlsrc

Using d3 data properties to set inner HTML to an img link


I'd like to be able to pass in an img src to inner html in a web application I'm building.

Here's an example of one item in my data:

{"ArtistImage": "https://photos.bandsintown.com/thumb/8697643.jpeg", "Address": "7000 Coliseum Wy, Oakland, CA 94621", "Artist": "Shawn Mendes"}

And the HTML I'm trying to insert the image:

<li>
    <a id="test" href="#">Image</a>
</li> 

And the JavaScript to dynamically change the inner HTML based on which data point I'm hovering over.

d3.selectAll(".events")
      .on("mouseover", function(d) {        
              document.getElementById("test").innerHTML = "<img src=\"d.ArtistImage\" width=\"400px\" height=\"150px\">";
          })

But it's reading a 404 error, image not found. How to I get this bit of JavaScript to pass the link in d.ArtistImage as a string to the inner HTML?


Solution

  • When you do this...

    "<img src=\"d.ArtistImage\" width=\"400px\" height=\"150px\">"
    

    ... you are saying that the src of that image is literally d.ArtistImage, which is clearly incorrect.

    You can do it easily with template literals. Or simply concatenating the strings:

    "<img src='" + d.ArtistImage + "' width='400px' height='150px'>"
    

    Finally, you don't need to use document.getElementById in a D3 code. One could argue that document.getElementById is faster than a D3 selection (which internally uses document.querySelector), but the difference is not significant and, what's more important, this is not idiomatic. Just use a D3 selection with html, which uses innerHTML internally:

    d3.selectAll(".events").on("mouseover", function(d) {        
        d3.select("#test").html("<img src='" + d.ArtistImage + "' width='400px' height='150px'>");
    })