Tips for altering the color of string outputs

Can you help me modify a function to display different colors based on the output? For instance, I want it to show in orange if the result is too low, and in red if it indicates obesity.

bmiCalculation() {
      var weight = parseInt(this.currentWeight);
      var height = parseInt(this.height) / 100;
      var bmi = weight / (height * height);
      let text = "";
      if (bmi < 18.5) {
        text =  bmi.toFixed(2) + "kg/m2" + " Too low :)";
      } else if (bmi >= 18.5 && bmi < 24.9) {
        text =  bmi.toFixed(2) + "kg/m2" + " Normal";
      } else if (bmi >= 25 && bmi < 29.9) {
        text =  bmi.toFixed(2) + "kg/m2" + " Too much";
      } else if (bmi > 30) {
        text =  bmi.toFixed(2) + "kg/m2" + " Obese";
      }

      return text;
    }

Answer №1

var BMI_STATUSES = {
  LOW: {
    message: 'Weight too low ;)',
    colorCode: 'red',
  },
  NORMAL: {
    message: 'Normal weight',
    colorCode: 'green',
  },
  HIGHER_THAN_NORMAL: {
    message: 'Excessive weight',
    colorCode: 'orange',
  },
  OBESE: {
    message: 'Obese',
    colorCode: 'red',
  },
};

new Vue({
  el: '#app',
  data: {
    currentWeight: undefined,
    height: undefined,
    bmiLevelColor: '',
  },
  computed: {
    calculateBMI() {
      var weight = parseInt(this.currentWeight, 10);
      var height = parseInt(this.height, 10) / 100;

      if (isNaN(weight) || isNaN(height)) {
        return;
      }

      if (weight <= 0 || height <= 0) {
        throw new RangeError('Weight and Height must be greater than zero.');
      }

      var bmi = weight / (height * height);
      var status;

      if (bmi < 18.5) {
        status = BMI_STATUSES.LOW;
      } else if (bmi >= 18.5 && bmi < 25) {
        status = BMI_STATUSES.NORMAL;
      } else if (bmi >= 25 && bmi < 30) {
        status = BMI_STATUSES.HIGHER_THAN_NORMAL;
      } else if (bmi >= 30) {
        status = BMI_STATUSES.OBESE;
      }

      this.bmiLevelColor = status.colorCode;

      return bmi.toFixed(2) + " kg/m2 - " + status.message;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  Current Weight <input v-model="currentWeight" />
  Height <input v-model="height" />
  <div :style="{ color: bmiLevelColor }">{{ calculateBMI }}</div>
</div>

Answer №2

To add some style to your text, enclose it within an HTML tag (div) and apply CSS styling like color.

Answer №3

To customize the appearance of your website, create a CSS file with the desired colors and styles. Next, implement JavaScript code such as add.classList to dynamically apply different classes based on specific values.

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

The Intersection Observer encountered an issue as it was unable to access the property 'current' since it was undefined

My current project involves the implementation of IntersectionObserver, but I am facing an issue where I receive the error message Cannot read property 'current' of undefined. Can anyone help me identify what might be causing this problem? useOn ...

Maintaining Vue Router's functionality by utilizing Vue router links within Vue3

Is there a way to maintain the state of first view components when routing between views, without resetting them? Thank you for any help in advance. <div> <div id="titleControl"> <router-link :to="{ name: 'controls& ...

What is the proper method for activating the lights in a traffic light sequence?

I've been working on creating a traffic light sequence where each time the "change lights" button is pressed, the light is supposed to change. However, I'm facing an issue where the code only displays the red light and doesn't switch to ambe ...

Create a personalized compilation process that eliminates the two-way binding

In my Angular 1.5.8 application, I have created an attribute directive called my-directive. I am trying to apply this directive to an element while passing two additional parameters - one with one-way binding (@) and the other with two-way binding (=). Ev ...

Tips for dynamically adding events to a tag within a custom grid component

Presenting a query: `<tr @click="rowevent != null?rowevent(row,this.$el):''" :class="index % 2 === 0?bodytrclass[0]:bodytrclass[1]">` I am wondering how I can dynamically add events based on data (props) without explicitly writing each ev ...

The VueJS component failed to import successfully

Trying a simple demo to explore VueJS components, but encountering an error when loading the page: Unexpected Token Import in this line import GISView from './components/GISView.vue'; If I remove this line, GISView is not defined. Using Laravel ...

I was working with node.js when I encountered the following issue: 'server' is declared but its value is never read.ts(6133) from the line "var server = app.listen(3000, listening);"

While working on the 8.6 lesson in the api2 folder, I encountered an error/bug. Upon inspection of my server.js file, I identified and rectified the issue. However, when I revisited the api1 folder for the 8.5 lesson, everything was functioning correctly a ...

Transfer a script from a view to application.js in Rails: Guide and Instructions

After conducting some research, I found a code that worked well for me in the view. However, I am looking to transfer it to application.js so that I can utilize it in various forms. Another issue I encountered is having two scripts performing the same fun ...

purging data from javascript objects

In my Node.js HTTP server, I am using 'connect' to build a web service that currently parses JSON requests into an Object, performs operations, and returns a synchronous response. The JSON data comes from an ecommerce cart and results in an Objec ...

Initiate a Gravity Forms form refresh after modifying a hidden field with jQuery

TO SUM IT UP: Is there a way in Javascript to activate an update on a Gravity Form that triggers the execution of conditional logic? ORIGINAL QUESTION: I'm using Gravity Forms and I have set up an "on change" event $('#gform_1').find(&apos ...

Node.js making an API request

I am encountering an issue with the following code snippet: const req = require("request"); const apiReq = req("http://example.com/car/items.json", (err, res, body) => { if (!err && res.statusCode === 200) { return JSON.parse(body); } } ...

Transform the default WordPress gallery into a stunning slideshow with FlexSlider 2 integration

Greetings, I am searching for a solution to modify the default WordPress gallery in order to integrate the FlexSlider 2 plugin. I specifically want to incorporate this module or feature from this link, but I have been unable to figure it out myself. Your ...

Using JavaScript to Apply CSS Styles in JSF?

Is it possible to dynamically apply a CSS style to a JSF component or div using Javascript? I have been searching without any success. Below is some pseudo code: <div style="myJSStyleFunction("#{myBean.value}")"> stuff </div> The function wo ...

In JavaScript, the return statement is used to halt the execution of any subsequent statements

I encountered a situation where I need to stop the execution of the next function call if the previous function has a return statement. However, I noticed that even though there is a return statement in the "b" function below, the next function call still ...

Struggling with integrating API response formatting in React and updating state with the data

This is the content found in the file 'Search.js' import React, { Component } from 'react'; import * as BooksAPI from './BooksAPI' class Search extends Component{ constructor(props){ super(props); this.state={ ...

What is the best way to disable list items in a UI?

Check out my assortment: <ul class="documents"> <li class="list_title"><div class="Srequired">NEW</div></li> <li class="doc_price>1</li> <li class="doc_price>2</li> <li c ...

Top Method for Incorporating Syntax Highlighting into Code Blocks - React Sanity Blog

I'm currently exploring the most effective method to incorporate syntax highlighting into my react sanity.io blog. Here's a look at the article component I've developed using react: import React, {useEffect, useState} from "react"; import ...

Show/hide functionality for 3 input fields based on radio button selection

I need assistance with a form that involves 2 radio buttons. When one radio button is selected, I want to display 3 text boxes and hide them when the other radio button is chosen. Below is the code snippet: These are the 2 radio buttons: <input type= ...

What are some techniques for obtaining the second duplicate value from a JSON Array in a React JS application by utilizing lodash?

Currently, I am tackling a project that requires me to eliminate duplicate values from a JSON array object in react JS with specific criteria. My initial attempt was to use the _.uniqBy method, but it only retained the first value from each set of duplicat ...

Vue component without local state in the constructor

Here is the code snippet: import Vue from 'vue' import s from 'vue-styled-components' import Test1x from './test1x' export default Vue.extend({ name:'test1', render(){ const Div=s.div` ` const test1 ...