What is the best way to tailor specific text in d3.js?

I need assistance with customizing the appearance of an asterisk added to the end of a template literal in d3js. I want to be able to independently adjust the size and color of the asterisk regardless of the variable it's attached to. Below is the code snippet.

svg.selectAll('.text')
    .data(data)
    .enter()
    .append('text')
      .attr('class', d => {
        const shortName = getChannelShortName(d.name).toLowerCase();
        const channelEnabled = disabledChannels.includes(shortName);
        return !channelEnabled ? 'label x-axis-conversion-rate' : 'label x-axis-conversion-rate-disabled'
      })
      .attr('text-anchor', 'middle')
      .attr('x', d => xScaleBottom(d.name) + (d.subsetValue > 9 ? 45 : 45))
      .attr('y', d => -50)
      .text(d => {
        const shortName = getChannelShortName(d.name).toLowerCase();
        const channelEnabled = disabledChannels.includes(shortName);
        return !channelEnabled ? `${d.conversationRate}%` : `${d.conversationRate}%*`
      });

Specifically pertaining to ${d.conversationRate}%*, I am looking for ways to modify the size and color of the asterisk.

Answer №1

To style text within SVG text elements, you can utilize an svg tspan, which allows you to adjust font size and color:

When working with a tspan element inside a text element, you have the ability to customize text position, properties, and font styles (MDN)

There are two approaches you can take to incorporate a tspan with the text. You can either append the tspan along with the text using

selection.append("text").html(string)
, where the string includes your desired tspan attributes like
<tspan font-size="10" fill="orange">text</tspan>
.

Alternatively, you can chain two appends together: one for adding and setting the text, and another for appending a tspan to the end of the text:

selection.append("text")
 .text(d=>d.someText)
 .filter(function(d) { return d.doesElementNeedAsterisk })
 .append("tspan")
 .text("*");

The latter approach is demonstrated in the code snippet below:

var data = [
  {text1:"text1",color:"steelblue",size:"30px",asterisk:true},
  {text1:"text2",color:"crimson",size:"40px",asterisk:true},
  {text1:"text3",asterisk:false},
 ];

var svg = d3.select("body")
  .append("svg");
  
svg.selectAll("text")
  .data(data)
  .enter()
  .append("text")             
  .attr("x", 20)
  .attr("y", (d,i)=> i* 50+50)
  .text(d=>d.text1)          
  .attr("font-size",20)
  .filter(function(d) {      
    return d.asterisk;       
  })
  .append("tspan")           
  .text("*")
  .attr("fill", d=>d.color)  
  .attr("font-size",d=>d.size);  
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

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

Having issues with importing images in Next.js using the Next Images package

Having trouble with importing images locally from the images folder. Error message: "Module not found: Can't resolve '../images/banner1.jpg'" https://i.stack.imgur.com/Dv90J.png Attempting to access images in ImagesSlider.js file at compo ...

Tips for avoiding the need to reload a single page application when selecting items in the navigation bar

I am in the process of creating a simple Single Page Application (SPA) which includes a carousel section, an about us section, some forms, and a team section. I have a straightforward question: How can I prevent the page from reloading when clicking on nav ...

Is it possible to use combox to deactivate the buttons?

My goal is to deactivate the button as soon as I select a value from the drop-down list. For example, here's what I have: <select name =""> <option> disable </option> <option> enable </option> </select> <input ...

Display 3 images with the carousel feature on the middle image

Currently, I am utilizing the jquery.jcarousellite plugin and attempting to make the second image active. Below is the code snippet I have tried: <div id="jcl-demo"> <div class="custom-container auto moreItems "> <a href="#" c ...

Issue encountered: Unable to locate the file "SignInScreen" within the directory "./src/screens/authScreens" as referenced in the file "App.js"

App.js: import { StyleSheet, Text, View, StatusBar } from "react-native"; import { colors, parameters } from "./src/global/styles"; import SignInScreen from "./src/screens/authScreens/SignInScreen"; export default function A ...

Bar Chart Data Label Problem with HighCharts

My goal is to have the label positioned outside the bar stack. I attempted to achieve this using the code below, but it seems to be inconsistent in its results. dataLabels: { enabled: true, color: '#333', ...

There seems to be a white space problem located beneath the header photo and the initial

I'm a beginner at coding and working on this project for fun. I'm almost done, but I can't get rid of a white space that's dividing my header from the first section. See the screenshot below: https://i.stack.imgur.com/a1flt.png Even af ...

Maintaining header and footer while calling a PHP form on the same page

I have a straightforward PHP form, named home.php, that submits to itself: <form action="home.php" method="post" enctype="multipart/form-data" id="AddImageForm"> The issue arises when home.php is accessed from the index.php file (located below). Up ...

Unusual actions observed in ajax rails form calculator with pre-filled values

I have a form calculator in Rails that utilizes AJAX without a database. While it functions properly, I have noticed some peculiar behavior which I would like to address. Firstly, I navigate to the /interest_calculator page Then, I input 10 into @first_0 ...

The object's key values were unexpectedly empty despite containing data

There's an issue with my object - it initially gets key values, but then suddenly loses them all. All the key values become empty and a message appears in the console for the object: "this value was evaluated upon first expanding. it may have ch ...

An error is thrown when trying to retrieve Objects: Uncaught TypeError - Object function ParsePromise()

By obtaining a Document object with its id, the following code proceeds to locate corresponding sections based on the object. The document identifies a Parse object and document.toJSON converts this into a Javascript object. Furthermore, sections represent ...

Can you please explain the distinction between the statements var a = b = 2 and var a = 2; var b = 2;

Whenever I try to declare a variable within a function, I encounter an issue. var b = 44; function test(){ var a = b = 2; } However, the following code works without any problems: var b = 44; function test(){ var a; var b = 2; } The global ...

Issue with Angular Factory not being invoked

I am currently using a tutorial to create a MEAN app with Google Maps. However, I have encountered an issue where the map is not appearing on the page. Surprisingly, there are no errors in the browser console and even when debugging with node-inspector, I ...

Tips for managing this JavaScript JSON array

Here is an example of a JSON array: var data = { name: 'Mike', level: 1, children: [ { name: 'Susan', level: 2, }, { name: 'Jake', level: 2 }, { name: 'Roy', level: 2 }, ...

Encase an asynchronous function inside a promise

I am currently developing a straightforward web application that manages requests and interacts with a SQL database using Express and Sequelize. My issue arises when I attempt to call an async function on an object, as the this part of the object becomes u ...

How does the use of nodejs, a server-side scripting language, tie into ReactJs or other front-end languages?

Can Node, being a server-side scripting language, be effectively utilized in the development of front-end applications such as npx create-react-app or npx create-nuxt-app? ...

Leveraging Emotion API in Video Content (JavaScript or Ruby)

Currently, I'm in the process of uploading a video to the Emotion API for videos, but unfortunately, I have not received any response yet. I managed to successfully upload it using the Microsoft online console. However, my attempts to integrate it in ...

A guide on resolving the TypeError 'download property of undefined' issue when using Puppeteer with browser.downloads.download

Using puppeteer, I am automating the login process to access my account on a content provider's site and download multiple zip files. After obtaining an array of links to download, I go through each link in a loop and utilize the browser.downloads.dow ...

Troubleshooting CSS compatibility issues in Firefox browser (or HTML rendering as plain text)

In a unique web page comparing two photos, the clicked one changes, but there's an issue in Firefox where HTML displays as text and links don't work. CODE:- * { box-sizing: border-box; } html { height: 100%; } body { height: 100%; mar ...

How to eliminate the gap below a CSS element by adjusting the top value

https://i.stack.imgur.com/Sn6Wx.png The three 'Replacement Options' sections are contained within a div with the class relative. The relevant CSS properties have been applied as shown below: .relative { top: -10rem; position: relative; ...